0

In my entity I have 4 columns A,B,C,D if i want all the columns with distinct D on it how can I do it with Linq? For example:

Col A =1  Col B=2  Col C=3  Col D=4
Col A =1  Col B=2  Col C=9  Col D=4

now when i do distinct on Col D i want to display either one of the record not both. Is there a way to do it in Linq I do not want to use looping statements to do this.

madhu.13sm
  • 344
  • 1
  • 2
  • 13

1 Answers1

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

Are you sure you don't want to write that simple loop :-)

Marty Neal
  • 8,741
  • 3
  • 33
  • 38