[英]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 然后在其他地方加载Excel电子表格作为这些对象的集合
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. 我正在加载的电子表格有3列和3000行,因此我的集合的大小为9000。电子表格中每个单元格都有一个Datacollection对象。
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.
我想我需要'rowNumber'的最大值,但是我不确定如何取回该值。
Many thanks, 非常感谢,
If the row numbers are consecutive and start from 1, you can simply use LINQ's Max
extension: 如果行号是连续的并且从1开始,则可以简单地使用LINQ的
Max
扩展名:
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: 但是,如果它们确实以任意数字而不是1开头,或者行号中有空格,则需要查找不同行号的计数:
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;
如果您确定每一行正好有三列,那么更快的方法当然是
var rowCount = _dataCol.Count / 3;
要获取rowNumber
的最大值,可以使用LinQ:
var rowCount = _dataCol.Max(x => x.rowNumber);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.