我想基於過濾器表達式比較兩個列表;不知道如何構造泛型方法的lambda表達式;請參閱下面的代碼;還是有更簡單的方法通過LINQ中的相交?使用表達式/ lambda比較/過濾兩個列表的通用方法
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Data d1 = new Data {Id = 1, Name = "One"};
Data d2 = new Data { Id = 2, Name = "Two" };
Data d3 = new Data { Id = 3, Name = "Three" };
Data d4 = new Data { Id = 1, Name = "One" };
Data d5 = new Data { Id = 2, Name = "Two" };
Data d6 = new Data { Id = 4, Name = "Four" };
List<Data> original = new List<Data> {d1, d2, d3};
List<Data> filterItems = new List<Data> {d4, d5, d6};
List<Data> result = original.FilterDataList(filterItems);
//How to call this method?
List<Data> genericCall = original.FilterList<Data>(filterItems, data => data.Id ?????????????)
}
}
public class Data
{
public long Id;
public string Name;
}
public static class Extensions
{
public static List<Data> FilterDataList(this List<Data> sourceList, List<Data> filterOutItems)
{
return sourceList.Where(p => filterOutItems.All(l => l.Id != p.Id)).ToList();
}
public static List<T> FilterList<T>(this List<T> sourceList, List<T> filterOutItems, Func<T, bool> filterExpression)
{
return sourceList.Where(p => filterOutItems.All(filterExpression)).ToList();
}
}
}
啊哈! Except擴展正是我需要的!謝謝你:-)是的FilterList是一個通用的方法,我一直在努力,(x,y)=> x.Id!= y.Id不會與Func一起工作,所以那裏我卡住了 –
2012-02-10 02:43:17