1

I see a number of examples to group by multiple columns. I get that.

I have a DataTable and I want to get the distinct rows based on specific fields.

For example this works: (there are more than these two fields in the table) but I want those that are distinct on these two, returning all the fields)

var rtable = myDataTable.AsEnumerable()
     .GroupBy(a => new { FirstId = a["FirstId"], SecondId = a["SecondId"] })
     .Select(a => a.First()).CopyToDataTable();

I have a list of columns and want to use my list of columns as those to group by. I also have these field name strings in a list.

Simple example:

 var groupMap = new List<MyMap>{
     new MyMap(){FieldName = "FirstId", SomeOtherThing= "Hi", IsUnique = true},
     new MyMap(){FieldName = "SecondId", SomeOtherThing= "Cats", IsUnique = true },
     new MyMap(){FieldName = "FirstName", SomeOtherThing= "Dogs", IsUnique = false},
     };

I want to use the groupMap property FieldName where IsUnique=true to create my columns to use to GroupBy. Since I have this list, how can I use it to create the GroupBy with this criteria? Its sort of trivial to retype stuff from the list but I have several of these and want a more generic solution based on the properties of the MyMap class lists.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • I don't understand the question, can you try and make it clearer? – BrokenGlass May 06 '17 at 23:24
  • Use the strings in the properties to identify columns in the linq, is that not clear? – Mark Schultheiss May 07 '17 at 00:39
  • You can use the `GroupBy()` overload that takes a custom `IEqualityComparer` implementation. Your question is really too broad, as there are a number of other options as well, and answering it would require writing not only the [mcve] you should have provided, but also the entire implementation. But hopefully, with the suggestion to use `IEqualityComparer`, you can see how that would work for you. If not, you should improve your question. – Peter Duniho May 07 '17 at 00:55
  • That said, your question appears to be a duplicate of https://stackoverflow.com/questions/26889348/grouping-by-multiple-keys-known-at-runtime and http://stackoverflow.com/questions/24463750/dynamically-create-anonymous-object-from-list-values-c-sharp – Peter Duniho May 07 '17 at 00:58

0 Answers0