[英]Order result using LINQ and cast type
I am trying to order a list and take the top item.我正在尝试订购清单并拿走最重要的物品。 I can't set it to the type I need it to be.
我无法将其设置为我需要的类型。
var testFiles = new List<FileProcessing>();
testFiles = GetAll(var1, var2, var3, var3);
result = testFiles.OrderByDescending(item => item.DateRowAdded).Take(1);
return result;
I've got compile time error我有编译时错误
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable to 'myType'.
无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“myType”。
Well, .Take(size)
returns a IEnumerable<T>
(not single T
) of size at most size
.好吧,
.Take(size)
最多返回一个大小为size
的IEnumerable<T>
(不是单个T
)。 So you can put either所以你可以把
var array = testFiles
.OrderByDescending(item => item.DateRowAdded)
.Take(1)
.ToArray();
return array.Length > 0
? array[0]
: SomeCustomDefaultValue; // when testFiles is empty
Or或者
return testFiles
.OrderByDescending(item => item.DateRowAdded)
.FirstOrDefault(); // when testFiles is empty
Please, note that 2nd version being conciser doesn't allow to provide (in general case) custom default value.请注意,简洁的第二个版本不允许提供(在一般情况下)自定义默认值。
Finally, if testFiles
is (very) long and thus sorting ( OrderByDescending
) is slow and memory consuming, you can try Aggregate
:最后,如果
testFiles
(非常)长,因此排序( OrderByDescending
)很慢并且 memory 消耗,您可以尝试Aggregate
:
return testFiles
.Aggregate((bestSoFar, current) => bestSoFar.DateRowAdded > current.DateRowAdded
? bestSoFar
: current);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.