简体   繁体   中英

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

I have a response with LIST<ValidationModel> validationDto;

I want to return the LIST<ValidationModel> with list of views contains where gtype=health only

I have done the following 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,

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.

Determines whether any element of a sequence exists or satisfies a condition.

You should use All instead

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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