简体   繁体   中英

how to insert this condition in linq query

this is my code:

   IEnumerable<Blob> sortedList = from element in source 
                                       let locationx = element.Rectangle.X
                                       let locationy = element.Rectangle.Y

                                       orderby locationy ascending, locationx descending

                                       select  element ;

and i want to insert this condition:

sorting elements that their difference is less than 5 and sort them to locationx ascending

locationy[index+1]-locationy[index]<5

example:

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

OK - really not sure if I've understood the question (see my comments) I'm making the assumption that my comment on your question is correct (you want to sort by Y first, but only in blocks of 5, and sort by X within those blocks)

Essentially I'm sorted by Y divided by 5 and cast to an int - so that (for example) 0-4 will sort together, as will 5-9, etc.

In (my preferred) extension syntax:

source
  .OrderBy(element=>(int)(element.Rectangle.Y/5))
  .ThenByDescending(element=>element.Rectangle.X);

Or, you prefer

 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 ;

If sort logic/algorithm you've mentioned is a some kind of business logic and well known requirements in scope of your Application, basically not an one time particular case, I would suggest to encapsulate this logic in a new class which implements IComparer<T> ( MSDN ) and use it together with generic List<T>.Sort() ( MSDN ) or even LINQ OrderBy() method. So you'll keep a code base more clear and decoupled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM