3

I have a list using this Linq query

filterEntities = (from list in filterEntities where list.Id== 0 && list.Id== 1 && list.Id == 3 && list.Id== 6 select list).OrderBy(r => r.Id).ToList();

Now this linq returns a list like

ID  Age
0    18
0    19
1    21
3    24
6    32
6    08

I want to generate a list using sum of same Id's which returns like

ID  Age
0    37
1    21
3    24
6    40

Please suggest me possible query

1
  • 3
    How can this list return any values whatsoever? How can an Id column be 0 AND 1 AND 3 AND 6 ? Did you mean to write OR (||)? Commented Apr 23, 2012 at 13:22

3 Answers 3

4

I think you are looking to use a group by like this

List<int> ids = new List<int>() { 0, 1, 3, 6 };

filterEntities = (from list in filterEntities 
                  where ids.Contains(list.Id)
                  group list by list.id into g
                  orderby g.Key
                  select new 
                  {
                    ID = g.Key,
                    Age = g.Sum(x => x.Age),
                  }).ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

I would clean up the query like this, because the long expression looks a bit confusing:

var idList = new List<int> { 0, 1, 3, 6};

filterEntities = from e in filterEntities 
                 where idList.Contains(e.Id)
                 group e by e.Id into g
                 select new { Id = g.Key, Sum = g.Sum(e =>e.Age) };

Comments

0
filterEntities =  filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id))
                                .Sum(c=>c.Age)
                                .GroupBy(r=>r.Id)                                   
                                .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.