c# - 如何使用 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# 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());
推荐阅读
- java - 如何通过 json 将本地图像(可绘制图像文件)显示到 cardview。我想离线加载图像而不是使用毕加索库
- c# - Shared method to return string only if needed
- python - gTTS 无法保存文件两次
- postgresql - PostgreSQL:从代码执行查询时“pq:关系列不存在”,但在控制台中工作正常
- mongodb - MongoDB sorting by date as type String
- java - 处理不稳定的反应式 API
- python - 在地图函数中除以 0
- python - 如何解决这个 Typeerror?
- android - 搜索 ListView 不起作用
- vba - Tranfser data between two closed workbooks without creating a new one