Get an alphabetical list of items in the collection using lambda / link?

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

I want to create another list of string objects, where each line represents the first letter or character (may be a number) in the DisplayName property for all objects in the original list, and I want the list to be great.

So, for example, if there were the following three objects in my list:

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

I would like to create another list containing the following three lines:

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

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

+4
source share
3 answers

Like this:

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

Edited

+3
source
 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 its lambda) returns only the first character of the display name of the object x . This creates an IEnumerable type string , which is then passed to Distinct() . This ensures that you have only unique items in the list. Finally, OrderBy ensures that your items are sorted alphabetically.

Please note: if each of the objects in the list has different types, you cannot simply call x.DisplayName . In this case, I would create an interface, possibly called IDisplayName , that implements DisplayName . Then you can use x => ((IDisplayName)x).DisplayName.Substring(0,1) in your lambda.

+1
source

or in request notation:

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

Source: https://habr.com/ru/post/1299036/


All Articles