比较List
以下是一个使用C#更新List的示例代码:
using System;
using System.Collections.Generic;
using System.Data;
public class Program
{
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public static void Main()
{
// 创建一个List对象
List myList = new List
{
new MyObject { Id = 1, Name = "Object 1", Description = "Description 1" },
new MyObject { Id = 2, Name = "Object 2", Description = "Description 2" },
new MyObject { Id = 3, Name = "Object 3", Description = "Description 3" }
};
// 创建一个DataTable对象
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Description", typeof(string));
dataTable.Rows.Add(1, "Object 1", "Updated Description 1");
dataTable.Rows.Add(2, "Object 2", "Updated Description 2");
dataTable.Rows.Add(4, "Object 4", "Description 4");
// 比较List和DataTable的值,并更新List
foreach (DataRow row in dataTable.Rows)
{
int id = Convert.ToInt32(row["Id"]);
string name = row["Name"].ToString();
string description = row["Description"].ToString();
// 查找List中与DataTable中的Id匹配的对象
MyObject myObject = myList.Find(obj => obj.Id == id);
if (myObject != null)
{
// 更新List中的对象的属性值
myObject.Name = name;
myObject.Description = description;
}
else
{
// 创建一个新的对象,并添加到List中
myList.Add(new MyObject { Id = id, Name = name, Description = description });
}
}
// 打印更新后的List的值
foreach (MyObject obj in myList)
{
Console.WriteLine($"Id: {obj.Id}, Name: {obj.Name}, Description: {obj.Description}");
}
}
}
在上面的示例中,我们首先创建了一个包含一些初始值的List和一个包含一些更新值的DataTable。然后,我们使用循环遍历DataTable的行,比较每一行的Id值,然后更新或添加到List中的相应对象。最后,我们打印更新后的List的值。