Linq Select具有相同汽车的用户

时间:2017-01-04 13:58:41

标签: c# linq group-by

我有User对象和Car对象,它们可以通过Order对象拥有多对多关系。我希望能够让所有拥有与user1相同的汽车的用户。如果我在SQL中写这个,那么下面会产生正确的结果

SELECT * FROM users 
WHERE id IN (SELECT userId 
             FROM orders WHERE carId 
             IN (SELECT carId FROM orders WHERE userId = 1)
             )
AND id != 1

如何使用List OrderList User的LINQ使用LINQ?

我的模特:

public class Order
{
    public int UserId { get; set; }
    public int CarId { get; set; }
}

我的代码:

 var orders = new List<Order>();
 orders.Add(new Order() { CarId = 1, UserId = 1 });
 orders.Add(new Order() { CarId = 1, UserId = 2 });
 orders.Add(new Order() { CarId = 2, UserId = 3 });
 orders.Add(new Order() { CarId = 2, UserId = 1 });
 orders.Add(new Order() { CarId = 3, UserId = 1 });
 orders.Add(new Order() { CarId = 4, UserId = 3 });

 var usersHasAnyCars = new Dictionary<int,int[]>();

 foreach (var user1 in orders.GroupBy(q=>q.UserId))
 {
         foreach (var user2 in usersHasAnyCars[user1.Key])
         {
            //my logic 
            //all users which have any car from cars of user1
         }
 }

例如:

  • for user id = 1 result is user id = 2 and id = 3
  • for user id = 2 result is user id = 1
  • for user id = 3 result is user id = 1

解决方案必须非常快,因为我有很多数据。 最好的解决方案是使用LINQ。

1 个答案:

答案 0 :(得分:3)

你可以替换你的2个foreach:

var usersHasAnyCars = orders.GroupBy(x => x.UserId).ToDictionary(x => x.Key, x => x.Count());

更新

作为对您评论的回复,您可以获得拥有属于User1的汽车的用户,如下所示:

var carsFromUser1 = orders.Where(o => o.UserId == 1).Select(o => o.CarId);
var usersHasAnyCars = orders.Where(o => carsUser1.Contains(o.CarId) && o.UserId != 1);