Group By First Letter of word with Linq

 

This is sample code which you can used to group some list of objects based on first letter of the object name or any string property.

In the following example I get list of contacts in an application and after getting those from DB , I group them with the First letter of the Contact name and order them in alphabetical order.

Following is my Contact Class.

  
 public class CardContactModel
    {
        public int CardId { get; set; }
        public string CardName { get; set; }
        public int? ContactId { get; set; }
        public JObject Information { get; set; }
        public string ProfileImage { get; set; }
        public string SharedTo { get; set; }
        public string RecievedFrom { get; set; }

    }

Then I group it and add it to a dictionary with the following line of code.

  
Dictionary> Contacts  = contacts.GroupBy(x => x.CardName.Substring(0, 1).ToUpper(), (Letter, Contacts) => new { Alphabet = Letter, SubList = Contacts.OrderBy(x => x.CardName).ToList() })
                .OrderBy(x => x.Alphabet).ToDictionary(x => x.Alphabet, x => x.SubList);
            return searchContactsResponse;

Hope this is helpful.

 

Happy Coding !!!

Comments

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5