简体   繁体   English

在 C# 中的列表内过滤 - 根据 where 条件选择

[英]filter inside list in C# -Select based on where condition

I have a response with LIST<ValidationModel> validationDto;我收到了LIST<ValidationModel> validationDto;

I want to return the LIST<ValidationModel> with list of views contains where gtype=health only我想返回带有视图列表的LIST<ValidationModel>仅包含其中gtype=health

I have done the following returnResult = validationDto.Where(a => a.Views.Any(i => i.gType == "health")).ToList();我已经完成了以下returnResult = validationDto.Where(a => a.Views.Any(i => i.gType == "health")).ToList(); but no luck.但没有运气。

Can any one please help here?有人可以在这里帮忙吗?

public class ValidationModel
{
    public MetadataDto Metadata { get; set; }
    public string Type { get; set; }
    public string PId { get; set; }
    public List<ListView> ListViews { get; set; }
}

public partial class ListView
{
    public string EType { get; set; }
    public string VName { get; set; }
    public string FName { get; set; }
    public string FType { get; set; }
    public string Path { get; set; }
    public string GType { get; set; }
    public string Enabled { get; set; }
    public bool IsTrue { get; set; }
}

Maybe change the string comparison to ignore case,也许将字符串比较更改为忽略大小写,

i.GType.Equals(groupType, StringComparison.OrdinalIgnoreCase)

This worked in LinqPad,这在 LinqPad 中工作,

var list = new List<ValidationModel>
{
    new ValidationModel { ListViews = new List<View>{ new View { GType="health" } } },
    new ValidationModel { ListViews = new List<View>{ new View { GType="health" } } },
};
var groupType = "health";
list.Where(a => a.ListViews.Any(i => i.GType.Equals(groupType, StringComparison.OrdinalIgnoreCase))).Dump();

I think you misunderstood the Any function.我认为您误解了Any function。

Determines whether any element of a sequence exists or satisfies a condition.确定序列的任何元素是否存在或是否满足条件。

You should use All instead您应该使用All

Determines whether all elements of a sequence satisfy a condition确定序列的所有元素是否满足条件

returnResult = validationDto.Where(a => a.Views.All(i => i.GroupType == groupType)).ToList();

Whenever you get confused by a complicated condition, you can extract the logic to its own method.每当您对复杂的条件感到困惑时,您都可以将逻辑提取到自己的方法中。 This allows you to test the method separately to ensure you got the logic right.这允许您单独测试该方法以确保您的逻辑正确。

I'm not crystal clear on your requirement but this seems about right:我对您的要求不是很清楚,但这似乎是正确的:

bool HasOnlyHealth(ValidationModel model)
{
    if (model.ListViews.Count != 1) return false;
    if (model.ListViews.Single().ToUpper() != "HEALTH") return false;
    return true;
}

Then pass the method as your delegate to the Where clause.然后将该方法作为您的委托传递给Where子句。

returnResult = validationDto.Where(HasOnlyHealth).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM