我需要一些帮助来过滤另一个对象列表中的对象列表。
当前,我能够过滤FirstLevel对象,使其仅返回与条件匹配的SecondLevel对象(列表中具有Id),如果碰巧具有ThirdLevel过滤器,则仅返回包含以下内容的SecondLevel对象:符合条件的ThirdLevel对象。
我需要的是ThirdLevel数组仅包含符合条件的数组。
我可以在单个Linq查询中做到这一点吗?
编辑:易于理解的(??)示例: 假设我有一个壁橱,在这个壁橱中,我有很多抽屉。现在,在这些抽屉中,我有几双袜子,每双袜子的颜色都不同。 我需要的是能够对抽屉进行过滤,以仅向我显示包含黑色袜子的那些,同时从抽屉中去除其他颜色。 (不知道是否合理)
下面是示例代码:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
List<int> filterSecondLevel = new List<int>(){1, 2};
List<int> filterThirdLevel = new List<int>(){3};
ThirdLevel _3a = new ThirdLevel(){Id=1};
ThirdLevel _3b = new ThirdLevel(){Id=2};
ThirdLevel _3c = new ThirdLevel(){Id=3};
ThirdLevel _3d = new ThirdLevel(){Id=4};
List<ThirdLevel> _3la = new List<ThirdLevel>(){_3a,_3b};
List<ThirdLevel> _3lb = new List<ThirdLevel>(){_3c,_3d};
SecondLevel _2a = new SecondLevel(){ Id=1, ThirdLevelList=_3la};
SecondLevel _2b = new SecondLevel(){ Id=2, ThirdLevelList=_3lb};
List<SecondLevel> _2la = new List<SecondLevel>(){_2a,_2b};
FirstLevel _1a = new FirstLevel(){ Id=1, SecondLevelList=_2la};
var result = _1a.SecondLevelList.Where(x =>
(filterSecondLevel.Count == 0 || filterSecondLevel.Contains(x.Id)) &&
x.ThirdLevelList.Where(y =>
filterThirdLevel.Count == 0 || filterThirdLevel.Contains(y.Id)
).ToList().Count > 0
).ToList();
}
}
public class FirstLevel
{
public int Id {get;set;}
public List<SecondLevel> SecondLevelList { get; set; }
}
public class SecondLevel
{
public int Id {get;set;}
public List<ThirdLevel> ThirdLevelList { get; set; }
}
public class ThirdLevel
{
public int Id {get;set;}
}
}
答案 0 :(得分:0)
您需要使用ANY()
var result = _1a.SecondLevelList.Where(x =>
(filterSecondLevel.Count == 0 || filterSecondLevel.Contains(x.Id)) &&
x.ThirdLevelList.Where(y => filterThirdLevel.Contains(y.Id)).Any())
.ToList();