Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in Query with Array in LINQ

I have array number = {2,3,4,5,6}

Now i have to select rows from table "dtlRecord" where this number is a column.

Number count
2      10
3      23
4      20

So what i need is

select sum(count) from dtlRecord where number in (2,3,4,5,6) group by number

I need above query in LINQ to SQL

like image 634
jvm Avatar asked Jan 27 '10 00:01

jvm


2 Answers

Use Enumerable.Contains:

int[] numbers = new[] { 2, 3, 4, 5, 6 };
var query = from r in dtlRecords
            where numbers.Contains(r.Number)
            group r by r.Number into g
            select new {
                Number = g.Key,
                Sum = g.Sum(r => r.Count)
            };

foreach(var result in query) {
    Console.WriteLine("Number = {0}, Sum = {1}", result.Number, result.Sum);
}
like image 181
jason Avatar answered Oct 21 '22 00:10

jason


How about just using inner join:

int[] numbers = new[] { 2, 3, 4, 5, 6 };

from r in dtlRecord
join number in numbers on r.Number equals number
group r by r.Number into g
        select new {
            Number = g.Key,
            Sum = g.Sum(r => r.Count)
        };

or

dtlRecord
    .Join(numbers, r => r.Number, number => number, (r, number) => new {r, number})
    .GroupBy(arg => arg.r.Number, arg => arg.r)
    .Select(g => new
    {
        Number = g.Key,
        Sum = g.Sum(r => r.Count)
    });
like image 23
Boris Lipschitz Avatar answered Oct 20 '22 22:10

Boris Lipschitz