如何将以下foreach循环转换为linq等效? foreach循环还是linq表现更好?这里的项目数量有限,可能在100s。提前谢谢。
System.out.println("~~~~~WELCOME~~~~~");
do{
do{
System.out.println("\nPlease enter item code");
System.out.print("#");
itemCode = br.readLine();
itemCodeCorrect = isItemCodeCorrect(itemCode);
}while(!itemCodeCorrect);
do{
System.out.println("\nPlease enter item description");
itemDesc = br.readLine();
itemDescCorrect = isItemDescCorrect(itemDesc);
}while(!itemDescCorrect);
do{
try{
System.out.println("\nPlease enter item weight");
itemWeight = Double.parseDouble(br.readLine());
}catch(NumberFormatException ex){
System.out.println("\n" +ex +"\nInvalid input. Item must be in a number format. Please try again");
}
}while(itemWeight == 0);
do{
try{
System.out.println("\nPlease enter the item price");
itemUnitPrice = Double.parseDouble(br.readLine());
}catch(NumberFormatException ex){
System.out.println("\n" +ex +"\nInvalid input. Item must be in a number format. Please try again.");
}
}while(itemUnitPrice == 0);
Allitems = new Items(itemCode, itemDesc, itemWeight, itemUnitPrice, quantity, Total, TotalCost, TotalWeight);
v.add(Allitems);
答案 0 :(得分:1)
您可以使用此查询使用匿名类型来存储中间结果:
List<ListItem> items = ListValueString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(lstItem => new { lstItem, listTexts = lstItem.Split(':') })
.Select(x => new ListItem()
{
ListText = x.listTexts[0],
ListId = Int32.Parse(x.listTexts[1]),
IsActive = true,
IsInUse = Int32.Parse(x.listTexts[1]) == _defaultString
})
.ToList();
var _ListItems = new ObservableCollection<ListItem>(items);
LINQ也使用循环,因此没有明显的性能差异。