1

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

(第一个参数)

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

1 回答 1

5

听起来您想按索引匹配列表元素。您可以从零迭代到列表元素的数量并通过其索引访问每个元素:

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

另一种方法是将所有内容压缩在一起:

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();
于 2012-10-15T00:41:54.910 回答