Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

How to write Linq Query for below SQL Query.

Select Count(ul.OriginId),ul.OriginId from UserLink ul
Where ul.OriginId is not null
group by ul.OriginId
having count(ul.OriginId)>1


Select ul.UserId from UserLink ul where ul.OriginId=123

Finally I want to return UserId group by OriginId but here I have written in two separate queries. 
Can we write above sql queries in single Linq query? please help me how to write  linq query in C#.

Thanks,
jayaram


What I have tried:

I am not able to use having in Linq.
Posted
Updated 16-Apr-19 9:22am
v2
Comments
[no name] 3-Apr-19 13:22pm    
How would you like that coded? Console app? Windows Forms? WPF? UWP? Xamarin? Mobile? Tablet? PC?

What should we call this program?

Would you like a database with that? SQL Server? Oracle? MySql?

What about an ORM?
haseebshah 4-Apr-19 4:12am    
Can you share table sample?

1 solution

Depending on what you're trying to achieve...

Try:
C#
var data = context.UserLink
    .GroupBy(x=>x.OriginId)
    .Where(grp=>grp.Key==123 && grp.Count()>1)
    .SelectMany(grp=>new
        {
             OriginId = grp.Key,
             UserId = grp.Select(u=> u.UserId)
             CountOfOriginId = grp.Count(),
         })
    .ToList();


Finally, i'd suggest to:
1) dowload 101 Linq samples[^]
2) download LinqPad[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900