Konzy262
Konzy262

Reputation: 3107

Count of properties in a collection of objects

I'm struggling how to get my head round this issue.

I have a class which stores cell information for each cell in a spreadsheet.

public class Datacollection 
{
    public int rowNumber { get; set; }
    public string colName { get; set; }
    public string colValue { get; set; }
}

Elsewhere I then load an excel spreadsheet as a collection of these objects

private static List<Datacollection> _dataCol = new List<Datacollection>();

The spreadsheet I'm loading has 3 columns and 3000 rows, so the size of my collection is 9000. One Datacollection object for each cell in the spreadsheet.

How might I get a row number count from this collection? I guess I would need the highest value of 'rowNumber' but I'm not sure how to get this value back.

Many thanks,

Upvotes: 0

Views: 365

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43896

If the row numbers are consecutive and start from 1, you can simply use LINQ's Max extension:

var rowCount = _dataCol.Max(cell => cell.rowNumber);

But if they do start at an arbitrary number instead of 1, or if there are gaps in the row numbers, you'd need to find the count of distinct row numbers:

var rowCount = _dataCol.Select(cell => cell.rowNumber).Distinct().Count();

If you are sure that every row has exactly three columns, a faster way would of course be var rowCount = _dataCol.Count / 3;

Upvotes: 2

Bojan B
Bojan B

Reputation: 2111

To get the max value of rowNumber you can use LinQ:

var rowCount = _dataCol.Max(x => x.rowNumber);

Upvotes: 1

Related Questions