Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - Linq query select distinct Order

I would like to get orders and joining another table and the problem is there's duplicate order returns.

Order table
Id  OrderNumber UserId
1   Ord123      U1
2   Ord124      U2
3   Ord125      U3
4   Ord126      U2

Authorize Customer Table
Id  UserId      CustomerId
1   U1      U2
2   U3      U2

Current Result for User: U1 (Power User) in viewing orders

Orders
Id  OrderNumber UserId
1   Ord123      U1
2   Ord124      U2
2   Ord124      U2
4   Ord126      U2
4   Ord126      U2

I want like this result

Id  OrderNumber UserId
1   Ord123      U1
2   Ord124      U2
4   Ord126      U2

So orders of User: U2(Customer) can be viewed by User: U1(Power User) and U3 (Support User). Below is my current implementation in querying orders.

 orders = 
    from items in ctx.Orders
    join auc in ctx.UserAuthorisedCustomers
    on items.UserId equals auc.CustomerId
    into jts
    from jtResult in jts.DefaultIfEmpty()
    where jts.Any(x => x.UserId == cri.UserId && x.CustomerId == items.UserId) 
      || items.UserId == cri.UserId
    select items;

And cri.UserId is User: U1

question from:https://stackoverflow.com/questions/66056770/linq-query-select-distinct-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are almost there, you just need to include the Distinct() function from your linq query, but to make sure you can adjust your SQL query data to C# code, you need to convert your linq query result to c# List() so the code would look like

 orders = 
from items in ctx.Orders
join auc in ctx.UserAuthorisedCustomers
on items.UserId equals auc.CustomerId
into jts
from jtResult in jts.DefaultIfEmpty()
where jts.Any(x => x.UserId == cri.UserId && x.CustomerId == items.UserId) 
  || items.UserId == cri.UserId
select items;

var distinct_orders = orders.ToList().Distinct();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...