Saturday 4 May 2013

C# Compare Generic List Collection Compare

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

namespace CompareLists
{
    class Program
    {
        static void Main(string[] args)
        {
List<string> myfirstList= new List<string>() { "One", "Two", "Three"};
List<string> mysecondList = new List<string>() { "One", "Four", "Three"};
List<string> myThirdList = new List<string>() { "One", "Four", "Three", "Five" };
List<string> myfourthList = new List<string>() { "One", "Two", "One", "Four", "Two" };

IEnumerable<string> newList= null;


// Compare two List<string> and display common elements

newList= myfirstList.Intersect(mysecondList , StringComparer.OrdinalIgnoreCase);

//OutPut in  newList

// Compare two List<string> and display items of myfirstList not in mysecondList
newList= myfirstList.Except(mysecondList , StringComparer.OrdinalIgnoreCase);
//OutPut in  newList

// Unique List<string>

newList= myfourthList .Distinct(StringComparer.OrdinalIgnoreCase);
//output in newList
// Convert elements of List<string> to Upper Case
newList= myfriestList.ConvertAll(x => x.ToUpper());

//output in newList

// Concatenate and Sort two List<string>

newList= myfirstList.Concat(mysecondList).OrderBy(s => s);
/output in newList
// Concatenate Unique Elements of two List<string>
newList= myfirstList.Concat(mysecondList).Distinct();
//Output in newList

 // Order by Length then by words (descending)         newList = mythirdList.OrderBy(x => x.Length)
                    .ThenByDescending(x => x);



/ /Create a string by combining all words of a List<string>
           
            string delim = ",";
            var strresult = myfirstList.Aggregate((x, y) => x + delim + y);
        

    // Create a List<string> from a Delimited string
            string s = "One Two Three";
            char separator = ' ';
            newList = s.Split(separator).ToList();          


// Convert a List<int> to List<string>

            List<int>listNum = new List<int>(new int[] { 3, 6, 7, 9 });
            newList = listNum .ConvertAll<string>(delegate(int i)
            {
               return i.ToString();
            });



 // Count Repeated Words
            var q = myfourthList.GroupBy(x => x)
               .Select(g => new { Value = g.Key, Count = g.Count() })
               .OrderByDescending(x => x.Count);

            foreach (var x in q)
            {
               Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
            }



// Reverse a List<string>
myfirstList.Reverse();

// Search a List<string> and Remove the Search Item
// from the List<string>

int Count= myfourthList.RemoveAll(x => x.Contains("Two"));
Console.WriteLine("{0} items removed", Count);


            Console.ReadLine();         
        }