[英]how to insert this condition in linq query
这是我的代码:
IEnumerable<Blob> sortedList = from element in source
let locationx = element.Rectangle.X
let locationy = element.Rectangle.Y
orderby locationy ascending, locationx descending
select element ;
我想插入这个条件:
对它们的差值小于 5 的元素进行排序,并将它们排序到 locationx 升序
locationy[index+1]-locationy[index]<5
例子:
Sorted(in my code) Desired
--------- ---------
x y x y
10 0 10 0
5 6 2 10
2 10 5 6
8 17 8 17
好的-真的不确定我是否理解了这个问题(请参阅我的评论) X 在这些块中)
本质上,我按 Y除以5 排序并转换为int
- 这样(例如)0-4 将排序在一起,5-9 等也将排序。
在(我的首选)扩展语法中:
source
.OrderBy(element=>(int)(element.Rectangle.Y/5))
.ThenByDescending(element=>element.Rectangle.X);
或者,您更喜欢
IEnumerable<Blob> sortedList = from element in source
let locationx = element.Rectangle.X
let locationy = element.Rectangle.Y
orderby (int)(locationy/5) ascending, locationx descending
select element ;
如果您提到的排序逻辑/算法是您的应用程序的 scope 中的某种业务逻辑和众所周知的要求,基本上不是一次性特殊情况,我建议将此逻辑封装在实现IComparer<T>
( MSDN ) 并将其与通用List<T>.Sort()
( MSDN ) 甚至LINQ OrderBy()方法一起使用。 因此,您将保持代码库更加清晰和解耦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.