我可以使用LINQ来仅检索“更改时"吗?价值观? [英] Can I use LINQ to retrieve only "on change" values?

查看:37
本文介绍了我可以使用LINQ来仅检索“更改时"吗?价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是构造一个LINQ查询,当其中一个字段发生更改时,该查询从一些DataRows中检索到我一些值.这是一个人为的例子来说明:

What I'd like to be able to do is construct a LINQ query that retrieved me a few values from some DataRows when one of the fields changes. Here's a contrived example to illustrate:

Observation   Temp  Time
------------- ----  ------
Cloudy        15.0  3:00PM
Cloudy        16.5  4:00PM
Sunny         19.0  3:30PM
Sunny         19.5  3:15PM
Sunny         18.5  3:30PM
Partly Cloudy 16.5  3:20PM
Partly Cloudy 16.0  3:25PM
Cloudy        16.0  4:00PM
Sunny         17.5  3:45PM

当观察值与上一个值相比发生变化时,我只想检索条目.因此结果将包括:

I'd like to retrieve only the entries when the Observation changed from the previous one. So the results would include:

Cloudy        15.0  3:00PM
Sunny         19.0  3:30PM
Partly Cloudy 16.5  3:20PM
Cloudy        16.0  4:00PM
Sunny         17.5  3:45PM

目前,有代码可以遍历DataRows并进行结果的比较和构造,但是希望使用LINQ来完成此操作.

Currently there is code that iterates through the DataRows and does the comparisons and construction of the results but was hoping to use LINQ to accomplish this.

我想做的是这样的:

var weatherStuff = from row in ds.Tables[0].AsEnumerable()
                   where row.Field<string>("Observation") != weatherStuff.ElementAt(weatherStuff.Count() - 1) )
                   select row;

但这不起作用-并且不会编译,因为这会在声明变量'weatherStuff'之前尝试使用它.

But that doesn't work - and doesn't compile since this tries to use the variable 'weatherStuff' before it is declared.

LINQ可以完成我想做的事情吗?在SO上,我没有看到其他类似的问题,但可能会错过.

Can what I want to do be done with LINQ? I didn't see another question like it here on SO, but could have missed it.

推荐答案

您可以使用带有索引的IEnumerable扩展名.

You could use the IEnumerable extension that takes an index.

var all = ds.Tables[0].AsEnumerable();
var weatherStuff = all.Where( (w,i) => i == 0 || w.Field<string>("Observation") != all.ElementAt(i-1).Field<string>("Observation") );

这篇关于我可以使用LINQ来仅检索“更改时"吗?价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆