Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all items belong to same type using LINQ

Tags:

c#

linq

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.

like image 981
Bhaskar Avatar asked Jun 11 '12 07:06

Bhaskar


People also ask

Can we use multiple where clause in LINQ?

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.

What is any () in LINQ?

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.

How use all in LINQ C#?

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.


3 Answers

You could use Distinct and Count:

isValid = products.Select(x => x.Type).Distinct().Count() == 1;
like image 123
Joey Avatar answered Oct 20 '22 07:10

Joey


You can check if all items have the same type as the first item:

bool isValid = products.All(x => x.Type == products.First().Type);
like image 41
dtb Avatar answered Oct 20 '22 06:10

dtb


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);
like image 6
Jeffrey Zhao Avatar answered Oct 20 '22 07:10

Jeffrey Zhao