Compare two List collection using C# in ASP.Net

Last Reply on May 31, 2017 07:12 AM By dharmendr

Posted on May 31, 2017 02:23 AM

Hi Team,

I have two list, Which has same data or some tiimes different data.

My requirement is if two list contains same data then need to some operation. So how to compare it.

Sample Data:

List 1:

var list1=new List<T>();

list1.Add(new PriceExcel{

Name="Test1",

Date="90",

Age="20"

});

 

List 2:

var list2=new List<T>();

list2.Add(new PriceExcel{

Name="Test1",

Date="90",

Age="20"

});

In above lists all the datas are same, So how to do comparison here. If all datas are not equal then i need to create new list else need not to create new list.

Any Help would be appriciated..

Posted on May 31, 2017 07:12 AM

Hi bebins,

Refer the below sample.

C#

protected void Page_Load(object sender, EventArgs e)
{
    var list1 = new List<PriceExcel>();
    var list2 = new List<PriceExcel>();

    list1.Add(new PriceExcel { Name = "Test1", Date = "90", Age = "20" });
    list2.Add(new PriceExcel { Name = "Test1", Date = "70", Age = "20" });
    bool isSame = false;
    for (int i = 0; i < list1.Count; i++)
    {
        string name1 = list1[i].Name;
        string date1 = list1[i].Date;
        string age1 = list1[i].Age;
        for (int j = 0; j < list2.Count; j++)
        {
            string name2 = list2[j].Name;
            string date2 = list2[j].Date;
            string age2 = list2[j].Age;
            if (name1.Equals(name2) && date1.Equals(date2) && age1.Equals(age2))
            {
                isSame = true;
                break;
            }
            else
            {
                isSame = false;
            }
        }
    }

    if (isSame)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Data with same value exist')", true);
    }
    else
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Data with same value not exist')", true);
    }
}

class PriceExcel
{
    public string Name { get; set; }
    public string Date { get; set; }
    public string Age { get; set; }
}