How to check if all items belong to 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 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.

Answers


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

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

You could use Distinct and Count:

isValid = products.Select(x => x.Type).Distinct().Count() == 1;

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 only want to check the type of each element in LINQ then -

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)));
}

Above example, checks the type of each element in array then gets the count of element from array which are not of class type A.

I hope you have same scenario and hope this helps !!


Need Your Help

EasyMock: test that method in mock isn't called

easymock

As per title, just wondering if there is a mechanism with easymock to test if a method wasn't called during it's lifetime.

How to rewrite a line in a CSV using python?

python csv

I'm having some trouble with my code - I have a csv file and I have to save the first line in the csv as a list. Then I have to clear the file and rewrite the line using the list. This is my code: