0

I have a collection which has items like InstId, PulseID and SheetID on top of other items. I would like to check if these values (as a combination) in the collection are distinct if they are not I would like to output them a simple trace message "Not Unique: InstId, PulseID and SheetID.

For e.g.,

InstId  |   PulseID     |   SheetID     |
-----------------------------------------
    1   |   1           |   99          |
    1   |   1           |   98          |
    1   |   1           |   97          |
    2   |   1           |   99          |
    2   |   1           |   98          |
    3   |   1           |   97          |
    2   |   1           |   99          |
    2   |   1           |   95          |
    3   |   1           |   93          |


    I would like a trace message which will output the duplicatite like 
    InstId:2, PulseID: 1, SheetID: 99

I was looking through this link and it seems to make sense but how do i get the ones which are not unique. C# Linq Group By on multiple columns

Community
  • 1
  • 1
Abe
  • 1,879
  • 2
  • 24
  • 39

2 Answers2

1

are you looking for something like this?

var result = IQueryableSource.GroupBy(x=>new {A=x.A, B=x.B, C=x.C}).Where(x=>x.Count()>1).Select(x=>x.Key);
DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
  • I am new to Linq, I cant quite understand what is x.key. I will try and implement this on my collection and see if it works. Cheers. – Abe May 09 '17 at 14:32
  • 1
    It would have been more readable as `elements.GroupBy(element => new { A = element.A, B = element.B }).Where(group => group.Count() > 1).Select(group => group.Key)`. Then it becomes (at least a little more) clear that `group.Key` is the anonymous object `{ A = element.A, B = element.B }` that you group by. – Tomas Aschan May 09 '17 at 15:03
  • This works perfectly fine. I have converted it to a list before using so that I can loop through. Solved. Thank you. – Abe May 10 '17 at 08:57
1

Given that the link uses query syntax, how about

var ans = from item in CollectionOfItems 
          group item by new { item.InstId, item.PulseID, item.SheetID } into ig
          where ig.Count() > 1
          select ig.Key;

You could also select ig.First() if you wanted the original collection item.

NetMage
  • 26,163
  • 3
  • 34
  • 55