【问题标题】:How can I return a list or enumerable of rows where column value has changed with Linq如何返回列值已随 Linq 更改的行的列表或可枚举
【发布时间】:2017-10-11 08:31:35
【问题描述】:

我有一个数据表:

Position Price
1        1.2
1        1.3
2        1.25
1        1.4
1        1.3
2        1.35

我想返回所有位置发生变化的行:

Position Price
2        1.25
1        1.4
2        1.35

有没有一种优雅的方法可以用 Linq 做到这一点?

我试过了:

var trades = Enumerable.Range(1, Data.Rows.Count - 1)
              .Where(i => !Data.Rows[i].Field<string>("Position").Equals(Data.Rows[i - 1].Field<string>("Position")));

但这会返回索引列表,而不是行。

【问题讨论】:

  • @Backs 请参阅问题编辑
  • 为什么你选择 2 两次但 1 只选择一次?
  • @Rahul 因为位置从 1 变为 2,然后变为 1,再变为 2...所以变化发生了 3 次... 2-1-2...

标签: c# linq datatable


【解决方案1】:

使用 LINQ:

var positionChanges = table.AsEnumerable()
    .Skip(1)
    .Where((row, index) => table.Rows[index - 1].Field<string>(0) != row.Field<string>(0));

【讨论】:

  • 完美。这就是我一直在寻找的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多