LINQ 按其子集合中的字段筛选集合
LINQ filter collection by filed in it's subcollection
我在下面定义了类:
public class AssignmentDictionaryDTOChildItem
{
public int id { get; set; }
public string text { get; set; }
}
public class AssignmentDictionaryDTO
{
public string BatchName { get; set; }
public List<AssignmentDictionaryDTOChildItem> ChildItems { get; set; }
}
并有一个模型作为 AssignmentDictionaryDTO 类型的列表。
现在我想按文本字段(来自 AssignmentDictionaryDTOChildItem)过滤我的模型
model = model.Where( x => x.ChildItems.SelectMany( y => y.text.ToLower().Contains( q ), z => z ) );
但它无法编译 - 抛出以下异常
The type arguments for method 'System.Linq.Enumerable.SelectMany<TSource,TCollection,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,System.Collections.Generic.IEnumerable<TCollection>>, System.Func<TSource,TCollection,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我知道,上面查询中的 z 是 AssignmentDictionaryDTOChildItem 类型,而我的模型是 AssignmentDictionaryDTO 类型的列表,所以它不适合。
那么我该如何修复我的查询以实现我上面提到的过滤?
怎么样:
model = model.Where(x => x.ChildItems.All(y => y.text.ToLower().Contains(q))).ToList();
//or Any instead of All
我在下面定义了类:
public class AssignmentDictionaryDTOChildItem
{
public int id { get; set; }
public string text { get; set; }
}
public class AssignmentDictionaryDTO
{
public string BatchName { get; set; }
public List<AssignmentDictionaryDTOChildItem> ChildItems { get; set; }
}
并有一个模型作为 AssignmentDictionaryDTO 类型的列表。
现在我想按文本字段(来自 AssignmentDictionaryDTOChildItem)过滤我的模型
model = model.Where( x => x.ChildItems.SelectMany( y => y.text.ToLower().Contains( q ), z => z ) );
但它无法编译 - 抛出以下异常
The type arguments for method 'System.Linq.Enumerable.SelectMany<TSource,TCollection,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,System.Collections.Generic.IEnumerable<TCollection>>, System.Func<TSource,TCollection,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我知道,上面查询中的 z 是 AssignmentDictionaryDTOChildItem 类型,而我的模型是 AssignmentDictionaryDTO 类型的列表,所以它不适合。 那么我该如何修复我的查询以实现我上面提到的过滤?
怎么样:
model = model.Where(x => x.ChildItems.All(y => y.text.ToLower().Contains(q))).ToList();
//or Any instead of All