LINQ Group By and Intersection between groups C#

240 Views Asked by At

I have the following list into C#:

table_schema | table_name | field_name | field_type
public         tableA       fieldA       character varying
public         tableA       fieldB       timestamp
public         tableA       fieldC       bytea
public         tableB       fieldA       character varying
public         tableB       fieldD       integer
other          tableC       fieldA       character varying
other          tableC       fieldE       integer

So the field with name fieldA and type character varying exists to all.

The output should be a list object :

field_name | field_type
fieldA       character varying
1

There are 1 best solutions below

5
Dmitry Bychenko On BEST ANSWER

I suggest GroupBy and then Aggregate all these groups while Intersecting their content:

var list = ...

var result = list
  .GroupBy(item => (item.table_schema, item.table_name),
           item => (item.field_name, item.field_type))
  .Select(group => group.AsEnumerable()) 
  .Aggregate((current, item) => current.Intersect(item))
  .ToList(); // <- Let's have a list of tuples

The only trick is line

   .Select(group => group.AsEnumerable()) 

We don't want to aggregate by IGrouping<K, V> but by more general IEnumerable<V>