locked
Select distinct on a list or collection?

    Question

  • Hi, can you select distinct on multiple fields in a generic list as follows?  I have a collection where I'd like select distinct ticker and companyname but it still returns the entire list.  The objects in the collection have other fields but I just want to pull a distinct list of these two data values.

     

    private IEnumerable<Company> GetDistinctCompanies(List<Company> companies)

    {

    IEnumerable<Company> distinctCompanies = (from c in companies

    select new Company

    {

    Ticker = c.Ticker,

    CompanyName = c.CompanyName

    }

    ).Distinct();

     

    return distinctCompanies.ToList();

    }

    Thursday, June 05, 2008 8:12 PM

Answers

  • Oh, my bad!

     

    Code Snippet

    IEnumerable distinctCompanies =

    from c in companies

    group c by new {c.Ticker, c.CompanyName} into g

    select new Company

    {

      Ticker = g.Key.Ticker,

      CompanyName = g.Key.CompanyName

    }

     

     

    Friday, June 06, 2008 1:41 PM

All replies

  •  

    http://msdn.microsoft.com/en-us/library/bb384063.aspx

     

     

     

    Code Snippet

    IEnumerable distinctCompanies =

    from c in companies

    group c by new {c.Ticker, c.CompanyName} into g

    select new Company

    {

      Ticker = g.Ticker,

      CompanyName = g.CompanyName

    }

     

     

     

     

     

    Thursday, June 05, 2008 8:40 PM
  • Thanks... tried to compile it but get:

     

    Error 1 'System.Linq.IGrouping<AnonymousType#1,Company>' does not contain a definition for 'Ticker' and no extension method 'Ticker' accepting a first argument of type 'System.Linq.IGrouping<AnonymousType#1,Company>' could be found (are you missing a using directive or an assembly reference?) 

     

    Error 2 'System.Linq.IGrouping<AnonymousType#1,Company>' does not contain a definition for 'CompanyName' and no extension method 'CompanyName' accepting a first argument of type 'System.Linq.IGrouping<AnonymousType#1,Company>' could be found (are you missing a using directive or an assembly reference?) 

     

    IEnumerable distinctCompanies =

    from c in companies

    group c by new {c.Ticker, c.CompanyName} into g

    select new Company

    {

      Ticker = g.Ticker, <!---ERROR 1

      CompanyName = g.CompanyName <!--ERROR 2

    }

    Friday, June 06, 2008 3:18 AM
  • Oh, my bad!

     

    Code Snippet

    IEnumerable distinctCompanies =

    from c in companies

    group c by new {c.Ticker, c.CompanyName} into g

    select new Company

    {

      Ticker = g.Key.Ticker,

      CompanyName = g.Key.CompanyName

    }

     

     

    Friday, June 06, 2008 1:41 PM