Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

c# - Group by multiple column into object and related lists

After searching i couldn't link any answer found on this site to my issue i have the following class

I have the following classes

public class Site
{
    public string  Name { get; set; }
    public string Stauts { get; set; }
    public string Demo { get; set; }
    public List<Data> Datas { get; set; }
}
public class Data
{
    public string IPT { get; set; }
    public string Currency { get; set; }
    
    public double Amount { get; set; }
}

I got data from external service in this format

    "Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "CATS",
"Currency": "EUR",
"Amount": "58.01",

"Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "ROS",
"Currency": "USD",
"Amount": "25.01",

"Name": "TcR",
"Stauts": "ACT",
"Demo": "BYD",
"IPT": "SAP",
"Currency": "EUR",
"Amount": "44.01",

How can i transform this data to have one site and all related Data object in a list?

what i did

var result = from d in Loc
                         group d by new
                         {
                             Name = d.Name,
                             Stauts = d.Stauts,
                             Demo = d.Demo,
                            
                         }
                                  into g
                         select new Site
                         {
                             Name = g.Key.Name,
                             Stauts = g.Key.Stauts,
                             Demo = g.Key.Demo,
                             Datas = g.ToList()/// ==> error here
 
                         };
question from:https://stackoverflow.com/questions/66063379/group-by-multiple-column-into-object-and-related-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuimng you have that values in a list named _list, here's what you could do:

var grouped = _list
    .GroupBy(item => new { item.Name, item.Status, item.Demo })
    .Select(g => new Site()
        {
            Name = g.Key.Name,
            Status = g.Key.Status,
            Demo = g.Key.Demo,
            Datas = g.Select(groupItem => new Data() 
                {
                    IPT = groupItem.IPT,
                    Currency = groupItem.Currency,
                    Amount = groupItem.Amount,
                }).ToList(),
        })
    .ToArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...