开发者

Get Alphabetical List Of Items in Collection Using Lambda/Linq?

开发者 https://www.devze.com 2022-12-17 22:33 出处:网络
I have a list of objects.Each object contains a property called \'DisplayName\'. I want to create another list of string objects, where each string represents the first letter or character (could be

I have a list of objects. Each object contains a property called 'DisplayName'.

I want to create another list of string objects, where each string represents the first letter or character (could be a number) in the DisplayName property for all obje开发者_开发百科cts in the initial list, and I want the list to be distinct.

So, for example, if my list contained the following three objects:

(1) DisplayName = 'Anthony' (2) DisplayName = 'Dennis' (3) DisplayName = 'John'

I would want to create another list containing the following three strings:

(1) 'A' (2) 'D' (3) 'J'

Any idea how to do this with minimal coding using lambda expressions or linq?


Like this:

list.Select(o => o.DisplayName[0].ToString())
    .Where(s => Char.IsLetter(s, 0))
    .Distinct().ToList();

Edited


List<myObject> mylist = new List<myObject>();
//populate list
List<string> myStringList = myList
    .Select(x => x.DisplayName.Substring(0,1))
    .Distinct()
    .OrderBy(y => y);

In the above code, Select (with it's lambda) returns only the first character from the display name of object x. This creates an IEnumerable of type string, which is then passed to Distinct(). This makes sure you have only unique items in the list. Finally, OrderBy makes sure your items are sorted alphabetically.

Note, if each of the objects in the list are of different types, you won't be able to just call x.DisplayName. In that case, I would create an interface, possibly called IDisplayName, which implements DisplayName. Then you should be able to use x => ((IDisplayName)x).DisplayName.Substring(0,1) within your lambda.


or in query notation:

var stringList = (from a in objectList 
                      select a.DisplayName.Substring(0,1)).Distinct();
0

精彩评论

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