我有一个这样的对象列表:
public static List<CategorySource> categorySource;
public static List<CategorySource2> categorySource2;
public class CategorySource
{
[PrimaryKey]
public int Id { get; set; }
public int GroupId { get; set; }
public string Name { get; set; }
public int SortOrder { get; set; }
}
public class CategorySource2
{
[PrimaryKey]
public int Id { get; set; }
public int GroupId { get; set; }
public string Name { get; set; }
}
是否有一种方法,我可以从categorySource列表中填充categorySource2列表,而无需进行Linq select和指定每一列就可以忽略SortOrder属性。
请注意,这些只是示例,因为我需要填写的列表具有40多个属性。
您可以尝试使用@Guy建议的继承来进行此操作:
static void Test()
{
categorySource.Add(new CategorySource { Id = 1, Name = "Test 1" });
categorySource.Add(new CategorySource { Id = 2, Name = "Test 2" });
categorySource.Add(new CategorySource { Id = 3, Name = "Test 3" });
categorySource.Add(new CategorySource { Id = 4, Name = "Test 4" });
categorySource2.AddRange(categorySource);
foreach ( var item in categorySource2 )
Console.WriteLine($"{item.Id}: {item.Name}");
}
public static List<CategorySource> categorySource = new List<CategorySource>();
public static List<CategorySource2> categorySource2 = new List<CategorySource2>();
public class CategorySource2
{
public int Id { get; set; }
public int GroupId { get; set; }
public string Name { get; set; }
}
public class CategorySource : CategorySource2
{
public int SortOrder { get; set; }
}
由于CategorySource是CategorySource2的类型,因此您可以在categorySource2列表中添加categorySource项目。
这样做称为多态性。
What is polymorphism, what is it for, and how is it used?
这样做,您可以在忽略SortOrder的同时操作项目。
但是我不确定我是否理解你的问题。