none
Linq using GroupBy RRS feed

  • Question

  • Hi

    I have a List<CollectionClass1> which has data as

    ID   NAME      Sub Id    Sub id name List
    1    A 2       R1 1,2
    1    A 3       R2 1,2
    1   A 4       R3 1,2

    now on this collection i need to write a groupby on ID or Name and get a single record of Class1 as follows.

    class1 {string id, string name, list<subclass>,string}

    note class subclass{string subId and String Subname};

    Please give a code of the query.

    Thanks in advance,

    Joseph

    Thursday, March 28, 2013 3:29 PM

Answers

  • Something like:

    var results = theList.GroupBy(cc => new { cc.ID, cc.NAME }).Select(g => new class1(g.Key.ID, g.Key.NAME, g.Select(item => new subclass(item.Sub_id_name, item.Sub_id)).ToList()));


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Joseph2023 Thursday, March 28, 2013 8:31 PM
    Thursday, March 28, 2013 4:41 PM

All replies

  • This will be something like:

    var results = theList.GroupBy(cc => new { cc.ID, cc.NAME }).Select(g => new class1(g.Key.ID, g.Key.NAME, g.ToList()));
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Thursday, March 28, 2013 3:55 PM
  • Hi Reed,

    Thanks for your reply. Please note class subclass has two fields{string subId and String Subname}; So i need to create a new list which is a collection of subclass also while generating the Class1.

    Please include that also in the code and give me.

    Thanks & Regards,

    Joseph

    Thursday, March 28, 2013 4:40 PM
  • Something like:

    var results = theList.GroupBy(cc => new { cc.ID, cc.NAME }).Select(g => new class1(g.Key.ID, g.Key.NAME, g.Select(item => new subclass(item.Sub_id_name, item.Sub_id)).ToList()));


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Joseph2023 Thursday, March 28, 2013 8:31 PM
    Thursday, March 28, 2013 4:41 PM
  • Hi Re,ed

    Thank you so much for your reply. but i want to copy another property from old collection to new collection, let us say already a propety of List collection as shown at top 1,2 column is also there, how to copy it as it is to the new collection?  Subclass is creating fine. Could you please suggest.

    Thanks a lot.

    Best Regards,

    Joseph.

    Thursday, March 28, 2013 8:33 PM