我正在尝试获取表中具有相同值的列中的所有行。我通过以下方式使用组来工作:
var groupedData = from row in Tab1Model.ExcelGridDataSource.AsEnumerable()
group row by row.Field<string>("A");
foreach (var group in groupedData)
{
if (group.Count() > 1)
{
//select from each group only the DataRows
//having a certain value in a second column
foreach (var dataRow in group)
{
multipleRowsList.Add(dataRow);
}
}
}
我想避免调用 foreach,只获取计数> 1 的组,然后仅获取具有具有特定值的第二列的数据行。谢谢!
试试这个:
var query = from row in excelDataSource
group row by row.Field<string>("A") into g
select new { Value = g.Key, Rows = g };
var nonZeroRows= from q in query
where q.Rows.Count() > 0
select q.Rows;
// at this point you have an enumerable of enumerables of tablerows.
var list = nonZeroRows.Aggregate(Enumerable.Empty<TableRow>(),
(a, b) => a.Concat(b.Where(c => c.Something == true)); // your condition here
谢谢阿塔纳米尔!这是最终的代码,只是想知道您是否有更好的方法。这样做的最终目标是标记输入两次的行之一。
var groupedData = from row in Tab1Model.ExcelGridDataSource.AsEnumerable()
group row by row.Field<string>("A")
into g
select new {Value = g.Key, Rows = g};
var nonZeroesRows = from q in groupedData
where q.Rows.Count() > 1
select q.Rows;
//at this point you have an enumerable of enumerables of tables rows
var listRows = nonZeroesRows.Aggregate(Enumerable.Empty<DataRow>(),
(a, b) => a.Concat(b.Where(c => c.Field<bool>("Omit Row") == false)));
//grouped them again and get only the last row from the group wiht a count > 1
var doubleRows = from row in listRows
group row by row.Field<string>("A")
into g
where g.Count() > 1
select g.Last();
或者也许更好:
var groupedData = from row in Tab1Model.ExcelGridDataSource.AsEnumerable()
group row by row.Field<string>("A")
into g
where g.Count() > 1
select new {/*Value = g.Key,*/ Rows = g};
//at this point you have an enumerable of enumerables of tables rows
var listRows = groupedData.Aggregate(Enumerable.Empty<DataRow>(),
(a, b) => a.Concat(b.Rows.Where(c => c.Field<bool>("Omit Row") == false)));
//grouped them again and get only the last row from the group wiht a count > 1
var doubleRows = from row in listRows
group row by row.Field<string>("A")
into g
where g.Count() > 1
select g.Last();