public class Product
{
public string Name {set; get;}
public string Type {set; get;}
}
public class ProductType
{
public string Name{get;set}
}
var products = GetProducts();
var productTypes = GetProductTypes();
bool isValid = products.All(x=>x.Type == ??) // Help required
I want to make sure that all products in the 'products' belong to only of the product type.
How could achieve this in linq. Any help is much appreciated I am struck with LINQ stuff ? Thanks.
Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.
You could use Distinct and Count:
isValid = products.Select(x => x.Type).Distinct().Count() == 1;
You can check if all items have the same type as the first item:
bool isValid = products.All(x => x.Type == products.First().Type);
var isValid = products.Select(p => p.Type).Distinct().Count() == 1;
or
var first = products.FirstOrDefault();
var isValid == (first == null) ? true : products.All(p => p.Type == first.Type);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With