Click here to Skip to main content
15,915,791 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a list which looks like following:
PartNumber ID
---------- --
ABC 1
ABC 2
ABC 3
XYZ 4
XYZ 5

I want to select all the IDs group by the PartNumber and join the ID into a string for further processing later in my system.
I have code before group by which looks like this:
string stringIDs = string.Join(",", myList.Where(x => x.ID != 0).Select(p => p.ID).ToList());


Therefore my "stringIDs" would look like "1,2,3,4,5" but it is not group by the PartNumber.

How should I modify my codes to make the final output to become something like:
PartNumber ID stringIDs
---------- -- ---------
ABC 1 1,2,3
ABC 2 1,2,3
ABC 3 1,2,3
XYZ 4 4,5
XYZ 5 4,5

Thank you.

What I have tried:

1. Tried changing the codes to become:
string stringIDs = string.Join(",", myList.Where(x => x.ID != 0).GroupBy(y => y.PartNumber).Select(p => p.ID).ToList());
but return error.
Posted
Updated 5-Aug-21 1:34am
Comments
Richard MacCutchan 4-Aug-21 4:40am    
"but return error."
What error?
Jamie888 4-Aug-21 4:49am    
The error is "IGrouping<string> does not contain a definition for "ID" and no accessible extension method "ID" accepting a first argument of type...."
Richard MacCutchan 4-Aug-21 7:22am    
What is the structure and content of myList?
Jamie888 4-Aug-21 4:50am    
The error happened at the .Select()

Your final output example seems to be just duplicating the information in a collection grouped by PartNumber. Here is an example of how to group your list.Each item in the list is split into a 2 element array from which a collection of value tuples of type (string id, string part) is constructed. That collection is grouped by id. The nested foreach loops just iterate over each group.


C#
  List<string> parts = new List<string> { "ABC 1", "ABC 2", "ABC 3", "XYZ 4", "XYZ 5" };
var grps=  parts.Select(s => s.Split(' ')).Select(a => (id:a[0],part: a[1])).GroupBy(v=>v.id);
foreach (var group in grps)
  {
      Console.WriteLine("Group {0}", group.Key);
      foreach (var p in group)
      {
          Console.WriteLine("  {0}", p.part);
      }
  }
 
Share this answer
 
Seems simple enough:
C#
var stringIDs = myList
    .Where(x => x.ID != 0)
    .GroupBy(x => x.PartNumber)
    .Select(g => new { PartNumber = g.Key, stringIDs = string.Join(", ", g.Select(x => x.ID)) })
    .ToList();
Or:
C#
var stringIDs = myList
    .Where(x => x.ID != 0)
    .GroupBy(x => x.PartNumber, (PartNumber, items) => new { PartNumber, stringIds = string.Join(", ", items.Select(x => x.ID)) })
    .ToList();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900