LINQ newbie question.
I would like to combine fields into a comma separated list when others are same in a list of objects. Not sure if I put the question correctly.
class A
{
int id;
int roll;
string name;
public A(int id, int roll, string name)
{
this.id = id;
this.roll = roll;
this.name = name;
}
}
class Program
{
static void Main(string[] args)
{
List<A> aList = new List<A>();
A a1 = new A(24, 501, "alex");
A a2 = new A(12, 27, "steven");
A a3 = new A(24, 67, "bob");
A a4 = new A(1, 90, "erin");
A a5 = new A(12, 27, "christy");
aList.Add(a1);
aList.Add(a2);
aList.Add(a3);
aList.Add(a4);
aList.Add(a5);
}
Since id and roll of a2 and a5 are same (12, 27), when creating a new list of objects, I would like to have one of its fields as (12, 27, "steven,christy") and rest just copied since there wasn't any match.
I am sorry if the question/explanation is confusion.
var res = aList
.GroupBy(z => new { z.id, z.roll })
.Select(z => new A(z.Key.id, z.Key.roll, string.Join(",", z.Select(z2 => z2.name))))
.ToList();
Do note id
, roll
and name
will have to be public
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.