![](/img/trans.png)
[英]C# Lists: How to copy elements from one list to another, but only certain properties
[英]Join two lists of objects: All properties from one list, only certain properties from the other one
我有兩個班級:
class Class1
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Amount { get; set; }
public string Category { get; set; }
}
class Class2
{
public id ProductId { get; set; }
public DateTime UpdateTime { get; set; }
public int ItemState { get; set; }
public decimal Price { get; set; }
public string ImageUrl { get; set; }
}
我為每個班級創建了兩個列表:
public List<Class1> listClass1 { get; set; } = new List<Class1>();
public List<Class2> listClass2 { get; set; } = new List<Class2>();
現在我想通過在連接兩個列表創建一個新的列表ProductID
包含來自所有屬性Class1
,只是UpdateTime
和ItemState
從Class2
。 做這個的最好方式是什么?
(最終目標是讓用戶保存當前會話以讓他以后繼續他的工作,為此我需要完整的listClass1
和提到的listClass2
屬性。想法是在合並列表上使用XmlSerializer
並保存它到一個 XML 文件中。要打開該文件,我想對其進行反序列化。如果您有更好的方法讓用戶保存他的會話,我會全力以赴。)
我建議創建一個代表連接參數集的第三個類。
public class Class1_2
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Amount { get; set; }
public string Category { get; set; }
public DateTime UpdateTime { get; set; }
public int ItemState { get; set; }
}
LINQ Join 2 Lists 中描述了如何 加入 2 個列表。 所以你最終會得到這樣的結果:
List<Class1_2> joinedList = (from item1 in listClass1
join item2 in listClass2
on item1.ProductId equals item2.ProductId
select new Class1_2
{
ProductId = item1.ProductId,
Amount = item1.Amount,
ProductName = item1.ProductName,
Category = item1.Category,
ItemState = item2.ItemState,
UpdateTime = item2.UpdateTime
}).ToList();
說明:您加入特定屬性上的項目。 如果它在兩個列表中相等,則獲取該項目並使用所選屬性構建一個新項目。 連接也可以在沒有Class1_2
情況下工作,但是您會得到dynamic
類型的結果。 新的Class_1_2
的優點是您可以將其用於具有定義結構的序列化。
編輯
您還可以在Class1_2
使用第二個構造Class1_2
public Class1_2(Class1 c1, Class2 c2)
{
ProductId = c1.ProductId;
Amount = c1.Amount;
ProductName = c1.ProductName;
Category = c1.Category;
ItemState = c2.ItemState;
UpdateTime = c2.UpdateTime;
}
這將把select
語句簡化為:
select new Class1_2(item1, item2)).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.