有没有一种 LINQ 方法可以根据数量将 2 个行项目变成 N 个行项目?

ken*_*nny 5 c# linq

下面的代码可以工作,但是有没有一种 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);
Run Code Online (Sandbox Code Playgroud)

xan*_*xan 6

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");
    }
}
Run Code Online (Sandbox Code Playgroud)