フィルタ式に基づいて2つのリストを比較したいと思います。ジェネリックメソッドのラムダ式をどのように構築するかわからない。下記のコードを参照してください。またはLINQの交差を介してより簡単な方法がありますか?式/ lambdaを使用して2つのリストを比較/フィルタする一般的な方法
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();
}
}
}
Aha !!例外エクステンションはまさに私が必要なものです!ありがとうございました:-)はいFilterListは、(x、y)=> x.Id!= y.IdはFuncで動作しませんでしたので、私が苦労していたジェネリックメソッドです –