当我有超过2列时,我怎么能分清楚?

时间:2012-10-30 16:41:58

标签: c# linq

在我的实体中,我有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中执行此操作我不想使用循环语句来执行此操作。

1 个答案:

答案 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;
   }
}

你确定你不想写那个简单的循环: - )