简体   繁体   中英

C# compare two Lists and update it's column values

I've got two C# lists (List listA and List listB) how can I compare these two and if duplicate (of specific columns ex. ID_num and ID_cust) is found then update column "ID_duplicate" which is value of listB's columns ID.

DataSet ds =  subMain;

List<string> listA = (from r in ds.Tables[0].AsEnumerable()
                      Select r.Field<string>("ID_num") + 
                       r.Field<string>("ID_cust")).ToList();

DataSet dsMain = Mains;

List<string> listB = (from r in dsMain.Tables[0].AsEnumerable()
                      select r.Field<string>("ID_num") + 
                      r.Field<string>("ID_cust")).ToList();

I want that listA will contain new column ID_duplicate with value ID_num from listB .

So that duplicates will be somehow linked with this ID_num .

I will then update that ID_duplicate to database.

Edit: Added more explanation in comment bellow.

If I understand is a join:

var listA = new List<Row> { 
    new Row { ID= 1, IdNum = 1, IdCust = 1 }, 
    new Row { ID= 2, IdNum = 1, IdCust = 2 }, 
    new Row { ID= 3, IdNum = 2, IdCust = 1 }, 
    new Row { ID= 4, IdNum = 1, IdCust = 3 }, 
    new Row { ID= 5, IdNum = 3, IdCust = 1 }, 
    new Row { ID= 6, IdNum = 4, IdCust = 1 } 
};

var listB = new List<Row> { 
    new Row { ID= 1, IdNum = 5, IdCust = 1 }, 
    new Row { ID= 5, IdNum = 6, IdCust = 2 }, 
    new Row { ID= 7, IdNum = 2, IdCust = 1 }, 
    new Row { ID= 9, IdNum = 1, IdCust = 3 }, 
    new Row { ID= 11, IdNum = 7, IdCust = 2 }
};

    var t = (from a in listA
             join b in listB on a.IdCust.ToString() + a.IdNum.ToString() 
             equals 
             b.IdCust.ToString() + b.IdNum.ToString()
             select new
             {
                ID = a.ID,
                IdUpdate = b.ID
             }).ToArray();

foreach (var item in t)
{
    Console.WriteLine("ID {0} IdUpdate {1}", item.ID, item.IdUpdate);
}

Here the Row class

class Row
{
    public int ID { get; set; }

    public int IdNum { get; set; }

    public int IdCust { get; set; }
}

Obviusly you can create a calculated column on Row class like this

public string ValueToCompare
{
   get
   {
      return this.IdNum.ToString() + this.IdCust.ToString();
   }
}

and use this on join for comparison

Max

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM