[英]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.