views:

137

answers:

3

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

+1  A: 

LINQ Equivalent Of Where IN
http://www.onedotnetway.com/linq-equivalent-of-where-in/

Robert Harvey
my number column are Guid datatype and when i execute query in Linqpad, it says Could not format node 'New' for execution as SQL
jatin
If your column is guid, why does your example show int numbers?
Robert Harvey
just wanted to give simple example
jatin
i tried to apply ToString() to both without any success
jatin
Check out Jason's example and substitute a guid array for the numeric array.
Robert Harvey
+3  A: 

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);
}
Jason
+1 because my answer appeared to confuse the OP. Maybe he'll have better luck with your example.
Robert Harvey
Thanks all. Resolved.
jatin
A: 

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)
    });
Boris Lipschitz