如何将列表参数添加到LINQ查询?

时间:2012-10-14 23:13:32

标签: c# linq list linq-to-entities

我有两个参数传递给方法,我需要将它们附加到最终查询列表。

(第一个参数)

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>();

1 个答案:

答案 0 :(得分: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();