c# List<T> data LINQ 动态查询 T 是任意类型
时间: 2024-03-08 13:45:52 浏览: 19
在 C# 中,可以使用泛型方法和类型参数来实现动态查询任意类型的 `List<T>` 数据。下面是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> intData = new List<int> { 1, 2, 3, 4 };
List<string> stringData = new List<string> { "Tom", "Jerry", "Mary", "John" };
int intResult = DynamicQuery<int>(intData, x => x > 2);
Console.WriteLine($"Int result: {intResult}");
string stringResult = DynamicQuery<string>(stringData, x => x.StartsWith("J"));
Console.WriteLine($"String result: {stringResult}");
}
static T DynamicQuery<T>(List<T> data, Func<T, bool> predicate)
{
return data.Where(predicate).FirstOrDefault();
}
}
```
在这个示例中,我们定义了一个泛型方法 `DynamicQuery`,它接受一个类型参数 `T` 和一个 `List<T>` 类型的数据 `data`,以及一个 `Func<T, bool>` 类型的谓词表达式 `predicate`。在方法内部,我们使用 LINQ 查询的 `Where` 方法和 `FirstOrDefault` 方法来实现动态查询。由于 `T` 是任意类型,因此可以对任意类型的数据进行动态查询。
在 `Main` 方法中,我们分别定义了一个 `List<int>` 类型的数据 `intData` 和一个 `List<string>` 类型的数据 `stringData`,然后分别调用 `DynamicQuery` 方法,传入不同的数据和谓词表达式,即可完成动态查询。
需要注意的是,在使用泛型方法和类型参数进行动态查询时,需要熟悉泛型和委托的语法和用法,才能正确使用这种技术。
希望这个答案能够解决您的问题。如果您有其他问题,可以继续提问。