这是我的问题的一个场景:我有一个数组,说:
{ 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 }
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的(数组元素=>它的计数):
4 => 1
1 => 2
3 => 2
2 => 1
5 => 1
3 => 1
2 => 2
Run Code Online (Sandbox Code Playgroud)
我知道这可以通过实现for loop.
但是谷歌使用LINQ使用较少的代码行没有成功,这使得这成为可能.
我希望能够做的是构建一个LINQ查询,当其中一个字段发生变化时,它会从某些DataRows中检索一些值.这是一个人为的例子来说明:
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
Run Code Online (Sandbox Code Playgroud)
当观察从前一个观察发生变化时,我只想检索条目.所以结果将包括:
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
Run Code Online (Sandbox Code Playgroud)
目前有代码迭代DataRows并进行结果的比较和构建,但希望使用LINQ来实现这一目标.
我想做的是这样的事情:
var weatherStuff = from row in ds.Tables[0].AsEnumerable()
where row.Field<string>("Observation") != weatherStuff.ElementAt(weatherStuff.Count() - 1) )
select row;
Run Code Online (Sandbox Code Playgroud)
但这不起作用 - 并且不会编译,因为它在声明之前尝试使用变量'weatherStuff'.
可以用LINQ做我想做的事吗?我在SO上没有看到像这样的另一个问题,但可能错过了它.