Home > Mobile >  Grouping Data with the same values on multiple properties
Grouping Data with the same values on multiple properties

Time:08-17

I have a list of objects with data. In order to analyze the data, n amount of properties must match and when they don't match, must be removed. This is regardless of the value of the properties, just that they are equal

For example:

C1 C2 C3 ...
1 bob 3 ...
1 bob 3 ...
1 bill 3 ... (this row would be removed)
1 bob 10 ... (this row would be removed)
1 bob 3 ...

I'm somewhat stuck and keep thinking I need to brute-force this. Is there anything in linq that can help? Self intersections?

CodePudding user response:

Assuming that you have an IEnumerable called items that contains all of your rows, and your property names are C1, C2, and C3, you could use GroupBy to do something like this:

var result = items
   .GroupBy(item => (item.C1, item.C2, item.C3))
   .Where(group => group.Count() > 1)
   .SelectMany(group => group);

This will do the following:

  • .GroupBy(item => (item.C1, item.C2, item.C3)) - create groups based on the three columns that you specified - any items where the three values are the same will be grouped together
  • .Where(group => group.Count() > 1) - filter out any groups that only have one item
  • .SelectMany(group => group) - "flatten" the groups back into a single list

You may need to adjust this so that it works with the actual types you are using, but hopefully you get the general idea.

  • Related