首页 > 解决方案 > 如何使用 ToList() 打印多个列表项?

问题描述

从列表中选择字段后尝试打印列表中的项目时,我收到一条错误消息,提示“无法从列表转换为项目”。一些查询有效,但有一些查询,例如下面列出的查询,需要不同的打印空白。我希望它能够在没有多个打印空白的情况下工作。

我尝试将 foreach 循环直接放在查询下,但它找不到要打印的正确项目。

 List<Item> items = new List<Item>();//create list

 items.Add(new Item()
            {

                ItemGroup = "Electric",
                ItemDescription = "Electric Sander",
                Quantity = 7,
                UnitPrice = 59.98f,
            });//add list item

 var totalValue = items
            .Select(x => (
                x.ItemDescription,
                x.Quantity,
                x.UnitPrice,
                x.Price = TotalValue((int)x.Quantity, (float)x.UnitPrice)
                ))
            .OrderBy(x => x.Quantity)
            .ToList();//create new list for question 1

         PrintItems(totalValue);//print item (throwing error "can't 
 //convert list to item"

  static void PrintItems(List<Item> items)//print void
    {
        foreach (var Item in items)
        {
            Console.WriteLine("" + Item);
        }
    }

标签: c#linq

解决方案


您正在使用 C# 7 功能使用 LINQ 创建元组Select,这意味着您不再拥有您的List<Item>类型,而是List<yourTupleType>.

如果这就是您要在 Select 中计算的全部内容,那么为什么不TotalValue直接Item上课

public class Item
{
    public string ItemGroup { get; set; }
    public string ItemDescription { get; set; }
    public int Quantity { get; set; }
    public float UnitPrice { get; set; }

    public float Price
    {
        get
        {
            // your TotalValue logic since you already have quantity and unit Price
            // something like
            return Quantity * UnitPrice;
        }
    }
}

然后您可以订购您的收藏并传递给 PrintItems 方法。

如果您想在类TotalValue之外使用方法,则另一种选择Item-不要创建新对象,而只需重新计算每个项目的价格。

items.ForEach(i => i.Price = TotalValue((int)x.Quantity, (float)x.UnitPrice));
PrintItems(items.OrderBy(i => i.Quantity).ToList());

推荐阅读