2012-10-14 58 views
1

我有兩個參數傳遞給方法,我需要將它們附加到最終查詢列表。如何將列表參數添加到LINQ查詢?

(第一個參數)

string[] Price= new string[5]; 
Price= new string[] { "50", "25", "35" }; 

(第二個參數)

List<string> DiscountPrice= new List<string>(); 
DiscountPrice.Add ("10"); 
DiscountPrice.Add ("5"); 
DiscountPrice.Add ("3"); 


var list= (from d in context.List 
      where .... 
      select new MyNewList 
      { 
       Name = d.Name,      
       Country = d.Country, 
       **Price = ??** //how do I attach the parameters one by one? In the order they were saved? 
       **DiscountPrice** = ?? 

      }).ToList<MyNewList>(); 
+0

你想使用這些參數作爲查詢參數或者只是將它們包含在結果中? (由你的問題,我假設最後) –

+0

你使用加入這些收藏?您是否希望添加單個價格和DiscountedPrice,或者您想要分配集合? – abhishek

+0

我只是想在結果中包含它們,將每個價格和折扣價格添加到集合中。我希望它是有道理的,thx – Ben

回答

4

這聽起來像你想匹配的索引列表中的元素。您可以從零迭代到列表中的元素的數量,並通過其索引來訪問每個元素:

var prices = new string[] { "50", "25", "35" }; 
var discountPrices = new List<string>() { "10", "5", "3" }; 

var items = (from d in context.List 
      where .... 
      select new { d.Name, d.Country }).ToList(); 

var list = (from index in Enumerable.Range(0, items.Count()) 
      select new MyNewList 
        { 
         Name = items[index].Name,      
         Country = items[index].Country, 
         Price = prices[index], 
         DiscountPrice = discountPrices[index] 
        }).ToList(); 

另一種方式是Zip都在一起:

var list = items.Zip(prices, (item, price) => new { item, price }) 
       .Zip(discountPrices, (x, discountPrice) => new { x.item, x.price, discountPrice}) 
       .Select(x => new MyNewList 
          { 
           Name = x.item.Name,      
           Country = x.item.Country, 
           Price = x.price, 
           DiscountPrice = x.discountPrice 
          }) 
       .ToList(); 
+0

謝謝你爲例子冒險。 – Ben

相關問題