Remove Items From Generic List Given Another List Using LINQ

Let’s say you have two lists and you want to remove the items from one list using the items from another.

This assumes both Lists are of the same type.

                
                FullList = (from a in FullList
                            where !RemoveList.Contains(a)
                            select a).ToList();
Advertisements

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)));