将列表从一个类转换为另一个类

时间:2018-09-19 15:28:21

标签: c# list linq

我正在尝试使用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的类,其中包含classA中的id以外的其他值(该类将保存所有不同属性的子集)

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>();
    }
}

我的要求是,在根据classAid分组之后,我需要将其转换为我的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

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

除了执行Select,选择新的Final并将组的Key用作Id并进行转换外,您应该能够使用现有的代码ac.ToListClassB的{​​{1}}列表中:

Details

答案 1 :(得分:0)

var finalobjList = obj.GroupBy(a => a.id).Select(x => new Final() { id = x.Key, details = x.Select(y => new classB() { Name = y.Name }).ToList() } ).ToList();

(仅提供代码答案-请不要讨厌我)

答案 2 :(得分:-1)

 var items = (from a in obj
 group new classB {Name = a.Name, phone = a.phone, interest = a.interest} by  a.id into aa
 select new Final { id = aa.Key, B= aa.ToList()}).ToList();