FLICKER FLICKER - 1 year ago 73
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();

I have many
. Some of them have the same

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

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
containing below objects

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download