FLICKER FLICKER - 1 month ago 7
C# Question

Select distinct of inner object using Linq

Searched couple of answers in SO but could not figure it out.

Using below classes

public class DbTable
{
public string Database { get; set; }
public string Schema { get; set; }
public string Name { get; set; }
}

public class DbColumn
{
public DbTable Table { get; set; }
public string ColumnName { get; set; }
}

List<DbColumn> cols = DataAccess.GetColumns();


In
cols
I have many
DbColumn
. Some of them have the same
Table


I want a list of Table but distinct on Database.Schema.Name

My
cols
looks like:

{"Col1", {"MyDB", "dbo", "Product"} }
{"Col2", {"MyDB", "dbo", "Product"} }
{"Col3", {"MyDB", "Sales", "Customer"} }
{"Col4", {"MyDB", "Sales", "Branch"} }
{"Col5", {"MyDB", "Sales", "Customer"} }
{"Col6", {"MyDB", "Sales", "Branch"} }


What I need is a
List<DbTable>
containing below objects

{"MyDB", "dbo", "Product"}
{"MyDB", "Sales", "Customer"}
{"MyDB", "Sales", "Branch"}

Answer

Linq should be able to do it. You'll need to do a Select projection followed by either a group-by or a lookup. Sort of like this:

var listOFTables = cols.Select(c => c.Table).ToLookup(k => k.Name, v=> v)
    .Select(k => k.First());

This will yield an IEnumerable<DbTable> that contains the 3 tables you are expecting.