這是有效的代碼,但是有沒有一種 LINQ 方法可以根據數量將 2 個行專案轉換為 N?
var list = new List<LineItem>{
new LineItem { Info = "two of these", Quantity = 2 },
new LineItem { Info = "one of these", Quantity = 1 }
};
// prints two lines
// 2x - two of these
// 1x - one of these
foreach( var entry in list) Console.WriteLine(entry);
Console.WriteLine("now I want three lines printed as for the shopping bag");
// prints threes lines quantity driving that
// 2x - two of these
// 2x - two of these
// 1x - one of these
// this works, but is there a clean LINQy way?
var bag = new List<LineItem>();
foreach( var item in list)
{
if ( item.Quantity == 1 )
bag.Add(item);
else
for ( var count = 0 ; count < item.Quantity ; count)
bag.Add(item);
}
foreach( var entry in bag) Console.WriteLine(entry);
uj5u.com熱心網友回復:
您可以使用的組合SelectMany()并Enumerable.Repeat()達到你想要的這里。例如:
var list2 = list.SelectMany(x => Enumerable.Repeat(x, x.Quantity));
SelectMany()從x輸入的每個元素中選擇一個元素。如果這些元素中的任何一個是序列本身,它們都將被展平為一個序列(而不是說以串列串列結束)Enumerable.Repeat()基于每個專案創建一個新的列舉,包含專案x重復x.Quantity次數。
在 .NetFiddle 上測驗的完整串列:https ://dotnetfiddle.net/wpOafs
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class LineItem
{
public string Info {get;set;}
public int Quantity {get;set;}
}
public static void Main()
{
var list = new List<LineItem>{
new LineItem { Info = "two of these", Quantity = 2 },
new LineItem { Info = "one of these", Quantity = 1 }
};
var list2 = list.SelectMany(x => Enumerable.Repeat(x, x.Quantity));
foreach(var item in list2)
{
Console.WriteLine(item.Info item.Quantity);
}
Console.WriteLine("Hello World");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/360551.html
