简体   繁体   中英

Filter values in linq orderby

Is there a way to filter the value -1 (from the IndexOf when txt not found in item) in the below query?

var sortedArray = array.OrderBy (item => item.IndexOf(txt)).ToArray();

Any pointers will be helpful.

If I use Where, it would be using IndexOf twice, is there a way to use IndexOf only once?

To avoid having to do the same IndexOf twice you can do:

var sortedArray = (from a in array
                  let i = a.IndexOf("txt")
                  where i >= 0
                  orderby i
                  select a).ToArray();

You can use Where to do your predicate, and then OrderBy later on.

var sortedArray =
    array.Where   (item => item.IndexOf("txt") != -1)
         .OrderBy (item => item.IndexOf("txt")).ToArray();

The easiest way is just to put a .Where() clause first.

var sortedArray = array.Where (item => item.IndexOf(txt) != -1)
                       .OrderBy (item => item.IndexOf(txt))
                       .ToArray();

This will probably cause a notable performance impact on large arrays or large data in the array, though, since you're now searching for it twice.

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