How to check if all elements belong to the same type using 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 all products in the "products" to belong only to the type of product.

How can this be done in linq. Any help is much appreciated, am I am amazed at LINQ stuff? Thank.

+5
source share
4 answers

You can check if all elements have the same types as the first element:

bool isValid = products.All(x => x.Type == products.First().Type);
+9
source

You can use Distinct and Count:

isValid = products.Select(x => x.Type).Distinct().Count() == 1;
+11
source
var isValid = products.Select(p => p.Type).Distinct().Count() == 1;

var first = products.FirstOrDefault();
var isValid == (first == null) ? true : products.All(p => p.Type == first.Type);
+6

LINQ, -

class A{
}

class B{
}

static void Main(string[] args)
{
       ArrayList arr = new ArrayList();
       arr.Add(new A());
       arr.Add(new A());
       arr.Add(new A());
       arr.Add(new B());
       arr.Add(new A());
       int count= arr.ToArray().Count(x=> !x.GetType().Equals(typeof(A)));
}

, , A.

, , !

0

All Articles