我需要为这个LINQ语句添加一个额外的过滤器,但我似乎无法正确
var _duplicateRows =
dt.AsEnumerable().GroupBy(
myRow =>
new
{
accidentYear = myRow.ItemArray[1].ToString().Trim(),
reviewLine = myRow.ItemArray[2].ToString().Trim()
}).Where(grp => grp.Count() > 1).Select(grp => grp.Key);
我需要的是排除accidentYear和reviewLine为Null或Empty
的行和行TIA
- 编辑
嘿伙计们,我只想更新帖子。在决定进行分组之前,我决定用它来清理数据表。public DataTable GetCleanDataTable(DataTable dt)
{
IEnumerable<DataRow> _query =
dt.AsEnumerable().Where(
dt1 =>
(!Convert.IsDBNull(dt1.ItemArray[0].ToString()) &&
!Convert.IsDBNull(dt1.ItemArray[1].ToString()) &&
!Convert.IsDBNull(dt1.ItemArray[2].ToString())));
return _query.CopyToDataTable<DataRow>();
}
答案 0 :(得分:2)
在数据表中添加where子句。
var _duplicateRows =
dt.AsEnumerable()
.Where(x=>!String.IsNullOrEmpty(myRow.ItemArray[1]) &&
!String.IsNullOrEmpty(myRow.ItemArray[2])
)
.GroupBy(
myRow =>
new
{
accidentYear = myRow.ItemArray[1].ToString().Trim(),
reviewLine = myRow.ItemArray[2].ToString().Trim()
})
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
更清洁的方法:
var _duplicateRows =
dt.AsEnumerable().Select(
s=> new {
accidentYear = s.ItemArray[1].ToString().Trim(),
reviewLine = s.ItemArray[2].ToString().Trim()
}
).Where(x=>!String.IsNullOrEmpty(accidentYear) &&
!String.IsNullOrEmpty(reviewLine)
)
.GroupBy(
myRow =>myRow
)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
答案 1 :(得分:1)
有时LINQ语法胜过扩展方法。
var _duplicateRows = from row in dt.AsEnumerable()
let accidentYear = row.Field<string>(0)
let reviewLine = row.Field<string>(1)
where (!string.IsNullOrWhiteSpace(accidentYear)
&& !string.IsNullOrWhiteSpace(reviewLine))
group row by new { accidentYear, reviewLine } into g
where g.Count() > 1
select g.Key;
答案 2 :(得分:0)