如何根据应用的子对象过滤器过滤父对象集合?
下面是我正在搜索具有 searchClientsList
中提到的所有客户端 ID 值以匹配子对象(即 UserClients 列表)的用户的场景。
我希望获得准确的 Linq 查询,以便在只有一个用户(用户 1001)符合所需条件的情况下获得预期结果。 以下是可以参考的示例代码片段。
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp1
{
class User
{
public int UserID { get; set; }
public List<UserClient> UserClients { get; set; }
}
class Client
{
public int ClientID { get; set; }
public int UserID { get; set; }
}
class UserClient
{
public int ClientID { get; set; }
public int UserID { get; set; }
public DateTime StartDate { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<int> searchClientsList = new List<int> { 1, 2};
List<User> users = GetTestData();
var result = users.Where(x => x.UserClients.Any(y => searchClientsList.Contains(y.ClientID) && y.UserID== x.UserID)).ToList(); //To work on Query.
Console.WriteLine("The above result should return list of users with userclients having all the clientIds mentioned in searchClientsList.");
Console.WriteLine("In this case, it should return only User1 when searchClientsList is [1,2].");
}
private static List<User> GetTestData() {
User user1 = new User()
{
UserID = 1001,
UserClients = new List<UserClient>() { new UserClient { UserID = 1001, ClientID = 1 }, new UserClient { UserID = 1001, ClientID = 2 } , new UserClient { UserID = 1001, ClientID = 3 } }
};
User user2 = new User()
{
UserID = 1002,
UserClients = new List<UserClient>() { new UserClient { UserID = 1002, ClientID = 2 }, new UserClient { UserID = 1002, ClientID = 3 } }
};
List <User> users = new List<User>();
users.Add(user1);
users.Add(user2);
return users;
}
}
}
答案 0 :(得分:1)
我无法弄清楚如何在单个 Linq 查询中执行此操作。
var result = users.ToList();
foreach(int clientId in searchClientsList)
{
result = result.Where(x => x.UserClients.Any(y => y.ClientID == clientId)).ToList();
}
获取原始列表的副本,然后为 searchClientsList
的每个成员减少它似乎是正确的方法。
答案 1 :(得分:1)
就像您在代码中提到的:上述结果应该返回具有 userclients 的用户列表,其中 所有 的 clientIds 在 searchClientsList 中提到>,所以你应该使用 .All 而不是 .Contains :
List<int> searchClientsList = new List<int> { 1, 2 };
List<User> users = GetTestData();
List<User> result = users
.Where(x => searchClientsList.All(clientId => x.UserClients.Any(y => y.ClientID == clientId && y.UserID == x.UserID)))
.ToList();
foreach (var user in result)
{
Console.WriteLine(user.UserID);
}
希望这对您有帮助。