我正在尝试将组转换为C#(使用Linq)中的复杂列表
public class classA
{
public string Name { get; set; }
public int id { get; set; }
public string phone { get; set; }
public string interest { get; set; }
}
classA
其中包含许多元素列表,如下所示。
List<classA> obj = new List<classA>();
obj.Add(new classA { id = 1, Name = "a", phone = "321", interest = "Playing" });
obj.Add(new classA { id = 1, Name = "2", phone = "123", interest="Tv" });
从这里我需要使用id来分组,所以我使用
Linq
var item = obj.GroupBy(a => a.id).Select(ac => ac.ToList()).ToList();
我还有一门课叫
classB
其中包含了
甲级
public class classB
{
public string Name { get; set; }
public string phone { get; set; }
public string interest { get; set; }
}
我的最后一堂课看起来像,
public class Final
{
public int id { get; set; }
public List<classB> details { get; set; }
public Final()
{
details = new List<classB>();
}
}
我的要求是,分组后
基于
id
,我需要把它转换成我的
final
班级。
所以我喜欢下面的内容,
public static void Main()
{
Console.WriteLine("Hello World");
List<classA> obj = new List<classA>();
obj.Add(new classA { id = 1, Name = "a", phone = "321", interest = "Playing" });
obj.Add(new classA { id = 1, Name = "b", phone = "123", interest = "Tv" });
obj.Add(new classA { id = 2, Name = "c", phone = "12322", interest = "Tv" });
obj.Add(new classA { id = 3, Name = "d", phone = "12333", interest = "Tv" });
var item = obj.GroupBy(a => a.id).Select(ac => ac.ToList()).ToList();
List<Final> finalobjList = new List<Final>();
foreach (var report in item)
{
Final finalObj = new Final();
foreach (var result in report)
{
finalObj.id = result.id;
}
var data = report.Select(x => new classB { Name = x.Name, phone = x.phone, interest = x.interest }).ToList();
finalObj.details = data;
finalobjList.Add(finalObj);
}
Console.WriteLine(finalobjList.Count());
}
我相信有另一个简单的方法来实现这一点
linq
不使用
foreach
谢谢你的帮助!