[英]Linq to get values from 2 list with one unique Id
我有一個班要綁定前。
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
現在,該類將從不同的表中獲取值,但是它們具有公共ID。
這是我正在循環中的列表。
var List1 = item.TicketTypes.Where(m => m.PerformanceID == item.Id)
.Select(t => new { t.Name, t.ID});
var List2 = item.Pricies.Where(m => m.PerformanceID == item.Id)
.Select(t => new { t.Price, t.ID });
item是每個循環實例的對象。
我想要的是
我希望MyClass列表按照其ID填充實體名稱和價格。
這里沒有太多信息可供我測試,但是我建議這樣做:
// Make sure to add a constructor to MyClass
var List1 = item.TicketTypes.Where(m => m.PerformanceID == item.Id)
.Select(t => new MyClass(t.Name, t.ID, item.Pricies.FirstOrDefault(p => p.PerformanceID == t.ID).Price));
這應該會給您期望的結果,但是就像我說的那樣,我沒有足夠的信息來測試這一點,因此請確保您對問題進行評論,以便我們將其解決。
在Linq語句中,如果我的假設正確(無法檢驗):
var result= from t1 in item.TicketTypes
join t2 in item.Pricies on t1.ID equals t2.ID
select new MyClass() { Id = t1.ID, Name = t1.Name, Price = t2.Price };
如果需要列表,請使用.ToList()
嘗試這個 :
var query = List1.Join(List2, l1 => l1.Id, l2 => l2.Id, (l1, l2) => new { ID = l1.Id, Name = l1.Name, Price = l2.Price });
foreach (var obj in query)
{
Console.WriteLine("{0} - {1} - {2}", obj.ID, obj.Name, obj.Price);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.