在我的实体中,我有4列A,B,C,D如果我想要所有具有不同D的列,我怎么能用Linq
来做?
例如:
Col A =1 Col B=2 Col C=3 Col D=4
Col A =1 Col B=2 Col C=9 Col D=4
现在,当我在Col D上做区别时,我希望显示其中一个记录而不是两个。
有没有办法在Linq
中执行此操作我不想使用循环语句来执行此操作。
答案 0 :(得分:0)
void Main()
{
//Your provided sample data
IEnumerable<Item> data = new Item[]
{
new Item{ A = 1, B = 2, C = 3, D = 4 },
new Item{ A = 1, B = 2, C = 9, D = 4 },
};
//Create a custom comparer for distinct'ing
CustomComparer comparer = new CustomComparer();
//Use the overload for distinct
IEnumerable<Item> distinctData = data.Distinct(comparer);
//Now we have a distinct list according to your comparer
foreach (var element in distinctData)
{
Console.WriteLine(element.C.ToString()); // => 3
}
}
//sample class that holds your data
class Item
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public int D { get; set; }
}
class CustomComparer : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{
return x.D == y.D;
}
public int GetHashCode(Item obj)
{
return obj.D;
}
}
你确定你不想写那个简单的循环: - )