【问题标题】:Linq - Create a set-length list with default values where emptyLinq - 创建一个设置长度列表,默认值为空
【发布时间】:2016-07-05 08:16:28
【问题描述】:

我知道这应该很容易做到,但是假设在我的 C# 应用程序中,我有一个 IEnumerable<string>,我需要使用 nulls 创建一个更大的枚举来获取额外的值。

所以,为了举例,假设我的可枚举有 12 个元素,我需要创建一个包含 24 个元素的最终列表(因此最后 12 个为空)。我知道我可以使用 for 循环对其进行编程,但必须有一种使用 Linq 的简单方法来执行此操作,我只是不确定使用哪种方法。

谢谢!!

【问题讨论】:

    标签: c# linq list merge


    【解决方案1】:

    这是我脑海中突然出现的第一件事:

    currentList = currentList.Concat(                 // build onto your current list
        Enumerable.Range(1, 24 - currentList.Count()) // number of elements needed
        .Select(i => (string)null));                  // what you want the element to be
    

    【讨论】:

    • 感谢您的详细解释,@Cory,我有点费解,但看起来你已经把它分解了,这将是一个很好的模式来了解如何在任何情况下都可以这样做。谢谢!!!
    【解决方案2】:

    Repeat.

    List<string> list = new List<string>() { "one", "two", "three" };
    list.AddRange(Enumerable.Repeat((string)null, 10));
    

    您可以这样做以获得 24 个元素。

    list.AddRange(Enumerable.Repeat((string)null, 24-list.Count()));
    

    【讨论】:

    • Addrange 和 Repeat - 简单且非常有意义!! - 非常感谢,@Nikki!
    【解决方案3】:

    我建议使用 Enumerable.Range 或 Repeat

    var list = yourList.Concat(Enumerable.Range(1, 24).Select(i => null)).Take(24);
    
    var list = yourList.Concat(Enumerable.Repeat(null, 24)).Take(24);
    

    【讨论】:

    • 非常感谢!! - 我真的喜欢take(24)的想法!
    • @JohnBus​​tos 这是最安全的,因为如果原始序列有超过 24 个项目(也不会潜在地重复原始序列两次),您不会遇到异常。唯一可能的警告是,如果它确实有超过 24 个,这将截断它,但这似乎相当合理。
    • 我可以看到...确实是最安全的方法。谢谢!
    • 请注意,var list 实际上是一个 IEnumerable,您需要调用 ToList 才能从中获取实际列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多