开发者

Lambda expressions - select operator

I would like to know how to write a Linq (using lambda Expression in standard dot notation) query. I have an array of some names, and I would like to retrevie a new array of names based on one statement. This is: Order the array of names, and return a new list from the name which starts on some specific letter (lets say letter M) on.

Thi开发者_StackOverflows is my current array:

string[] arrNames = { "Mike", "Zach", "Ella", "Allan", "Jo", "Roger", "Tito" };

I would like to return names like this: Mike, Roger, Tito, Zach - these 4; Other 3 names (Allan, Ella and Jo are names which start with a letter that are in the alphabetica order bellow letter "M". This is not the same as using Operator "StartsWith". This one only selects the names started on the specific letter. I would like to get all the names which are in alphabetical order from this letter and on (so names started from M to Z).

So retun list with names starts with letter "M" or above looking on the alphabetical order.

Mitja


var result = arrNames.Where(i => String.Compare("M", i) <= 0)
                     .OrderBy(i => i);


Looks like you need this:

arrNames.Where(n => string.Compare(n, "M") >= 0)

which returns all the names alphabetically greater (or equal) "M", in the default order ({ Mike, Zach, Roger, Tito } in your case).

If you want to sort it additionally, use

arrNames.Where(n => string.Compare(n, "M") >= 0).OrderBy(n => n)

This gives { Mike, Roger, Tito, Zach }.


arrNames.Where(s => string.Compare(s,"M",StringComparison.InvariantCultureIgnoreCase) >= 0).OrderBy(s => s);

if you want case-insensitive comparisons. Or use StringComparison.InvariantCulture for case-sensitive. It is usually a good idea to specify the culture for string comparisons (e.g. you can use the current culture, or the invariant culture).

If your whole point of sorting is just to get at the items beyond "M", then you may omit the OrderBy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜