Sorting Lists With Linq and Lamdas

Function to Sort List by “Text” property using Linq

        private List<TVEntity> sortTVObject(List<TVEntity> tvs)
        {
            var sortedTVs =
       from t in tvs
       orderby t.Text
       select t;

            return sortedTVs.ToList();
        }

TVEntity.cs (Object)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace com.dereksandbox.bl.Entities
{
    [Serializable]
    public class TVEntity
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }
}

Execution

            List<TVEntity> TVs = new List<TVEntity>();

            // create some dummy data
            TVs.Add(new TVEntity() { Text = "Samsung", Value = "1" });
            TVs.Add(new TVEntity() { Text = "LG", Value = "2" });
            TVs.Add(new TVEntity() { Text = "Song", Value = "3" });
            TVs.Add(new TVEntity() { Text = "Apex", Value = "4" });
            TVs.Add(new TVEntity() { Text = "Olevia", Value = "5" });
            TVs.Add(new TVEntity() { Text = "Mitshibi", Value = "6" });
            TVs.Add(new TVEntity() { Text = "Sharp", Value = "7" });

            SortedAvailableChoices = sortTVObject(TVs);

You could also use Lamda’s to perform the sorting as well:


List<TVEntity> TVs = new List<TVEntity>();

// create some dummy data
TVs.Add(new TVEntity() { Text = "Samsung", Value = "1" });
TVs.Add(new TVEntity() { Text = "LG", Value = "2" });
TVs.Add(new TVEntity() { Text = "Song", Value = "3" });
TVs.Add(new TVEntity() { Text = "Apex", Value = "4" });
TVs.Add(new TVEntity() { Text = "Olevia", Value = "5" });
TVs.Add(new TVEntity() { Text = "Mitshibi", Value = "6" });
TVs.Add(new TVEntity() { Text = "Sharp", Value = "7" });           

// sort using a Lamda expression
TVs.Sort((x, y) => (x.Text.CompareTo(y.Text)));  

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s