Dumbo
Dumbo

Reputation: 14122

How to find/compare a class property in a List<class>

I have a class like this which stores some data to later make a ListView:

public class ListData
{
   public string Name{get; set;}
   public int ColumnsNumber{get; set;}
   //And some other stuff!!
}

Now, I have List<ListData> datas which contains lots of instances of the above class. For making the ListView in detail mode, I need to know the maximum number of required columns. How can I check for this?

At the moment I have:

int max = 0;
foreach(ListData data in datas)
{
  if (data.ColumnsNumber > max) max = data.columnsNumber;
}

This seems to work, but is there a better way, or built in method or something in C# for doing this?

Upvotes: 3

Views: 600

Answers (5)

doc92
doc92

Reputation: 89

For people that prefers the non-lambda version:

int max = (from d in datas
           select d.ColumnsNumber).Max();

Upvotes: 2

harriyott
harriyott

Reputation: 10645

Use Linq:

var max = datas.Any() ? datas.Max(data => data.ColumnsNumber) : 0;

Upvotes: 0

Vladimir Perevalov
Vladimir Perevalov

Reputation: 4157

you can use LINQ for this:

var max = datas.Select(d => d.ConlumnsNumber).Max();

By this line, you tell LINQ, to map your ListData elements collection into ColumnsNumber collection, and then call Max() which a aggregation method. In order for this to compile you should add using System.Linq

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39898

You could use a Linq Query:

int max = datas.Max(data => data.ColumnNumbers);

Upvotes: 0

default locale
default locale

Reputation: 13456

Try LINQ. Enumerable.Max method, for example:

int max = datas.Max(d => d.ColumnsNumber);

This method throws an exception if collection is empty, though.

Upvotes: 0

Related Questions