[SOLVED] Convert SQL to Linq using group by

Issue

This Content is from Stack Overflow. Question asked by cegano

I am beginner in linq, want to convert sql query.

select UserId from Table where sID in(123, 124) group by UserId having count( distinct sID)=2

I tried like this

var abc= obj_map.dbset.where(x=>sID.Contains(x.sID.ToString())).Select(m=>UserId).Distinct().ToList();

How I can solve this?



Solution

You probably want something more like this:

int[] sIDs = new[] { 123, 124 };

IEnumerable<IGrouping<string, X>> abc =
    obj_map
        .dbset
        .Where(x => sIDs.Contains(x.sID))
        .GroupBy(x => x.UserId)
        .Where(gs => gs.Count() == 2);


This Question was asked in StackOverflow by cegano and Answered by Enigmativity It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?