我有一张有许多栏的纸。假设我有下面6列。实际列数更多
x temp 1 temp 2 temp 3 temp 4 temp 5 temp 6
101 22
102 23 34
103 56
104 34 56 78 98
105 11
106 12 32 43
107 2 5 89 99 101 123
在这个例子中,我想对最后一列的值求和,这个值是22+34+56+98+11+43+123
我用的是linqtoexcel,但不知道怎么做。
var ff = database.Where(w => BetweenTwoDates(txt_fromDate.Text, w["Time Column"].ToString(), txt_toDate.Text) == true);
var grouped = ff.GroupBy(row => row["Sample column"].ToString());
foreach (var g in grouped)
{
X.Add(g.Key);
var temp = g.Where(w => w["Temp "].ToString() != "");
Y.Add(g.Sum(a => (double.Parse(a["Temp"]))));
}
最佳答案
将IEnumerable转换为DataTable
并尝试以下代码,
int _total = 0;
foreach (DataRow _dr in dt.Rows) // Looping Rows
{
int _value = 0;
int _colCount = 1;
foreach (var _column in _dr.ItemArray) // Looping Columns
{
if (_column.ToString() != "")
{
//if column value is not equal to blank , keep assign it to _value
_value = Int32.Parse(_column.ToString());
}
else
{
//if column value is equal to blank , sum-up the _total with _value and break column looping and go to next row
_total += _value;
break;
}
if (_colCount == _dr.ItemArray.Length)
{
_total += _value;
break;
}
_colCount++;
}
}
这里,
dt
是转换后的DataTable
值,_total
将是您需要的结果。希望对你有帮助:)
编辑
这是如何转换为数据表的,
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
关于c# - 检索最后一列在Excel中有值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29027164/