简体   繁体   中英

LINQ: Select a column based on another column value

After executing some LINQs, I have this data as IQueryable of an anonymous type:

Cat  Type  Count
----------------
A     1     10
B     1     15
C     1     25
D     1     5
A     2     15
C     2     30
D     2     20
B     2     10

Now, for every Cat I want to select Count based on Type values with LINQ.

Output should be like this:

Cat  Type1Count  Type2Count
---------------------------
A       10           15
B       15           10
C       25           30 
D       5            20

You can try to use groupby then select to do pivot.

var query = myList
    .GroupBy(c => c.Cat)
    .Select(g => new {
        Cat  = g.Key,
        Type1Count = g.Where(a => a.Type == 1).Sum(c => c.Count),
        Type2Count = g.Where(a => a.Type == 2).Sum(c => c.Count)
    });

c# online

Result

Cat:A  Type1Count:10  Type2Count:15
Cat:B  Type1Count:15  Type2Count:10
Cat:C  Type1Count:25  Type2Count:30
Cat:D  Type1Count:5  Type2Count:20

So basically you need to group by Cat and Type and get sum of Count:

myList.GroupBy(x => new { x.Cat, x.Type }).Select(x => new { Cat = x.Key.Cat, Type = x.Key.Type, CountForTypeAndCat = x.Sum(y=>y.Count) })

This will allow you go get information for any Type not only 1 and 2

foreach (var item in query.OrderBy(x=>x.Cat).ThenBy(x=>x.Type))
{
     Console.WriteLine(string.Format("Cat:{0}  Type:{1}  CountForTypeAndCat:{2}", item.Cat, item.Type, item.CountForTypeAndCat));
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM