0

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"}         
FLICKER
  • 6,439
  • 4
  • 45
  • 75

3 Answers3

1

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.


EDIT: I skipped the part of the question that specified uniquness by Database, Schema, and Name. This can be easily implemented with a minor change to the above LINQ query:

var listOFTables = cols.Select(c => c.Table)
    .ToLookup(k => new {k. Database, k.Schema, k.Name}, v=> v)
    .Select(k => k.First());
code4life
  • 15,655
  • 7
  • 50
  • 82
0

I'm pretty sure you can accomplish this with a custom comparer. See this answer.

Community
  • 1
  • 1
jos76
  • 141
  • 1
  • 2
  • 8
0

try this:

  List<DbTable> ListDistinctTable = listcolum.Select(x => new { x.Table.Database, x.Table.Name, x.Table.Schema })
                                                    .Distinct()
                                                    .Select(x => new DbTable() { Database = x.Database, Name = x.Name, Schema = x.Schema })
                                                    .ToList();
Esperento57
  • 16,521
  • 3
  • 39
  • 45