Reputation: 75
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; }
}
Upvotes: 0
Views: 786
Reputation: 52240
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();
Upvotes: 0
Reputation: 143
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();
Upvotes: 1
Reputation: 1336
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();
Upvotes: 0