【问题标题】:Syntax for initializing a List<T> with existing List<T> objects使用现有 List<T> 对象初始化 List<T> 的语法
【发布时间】:2009-09-10 11:50:42
【问题描述】:

是否可以用 C# 中的其他列表初始化列表?假设我已经列出了这些:

List<int> set1 = new List<int>() {1, 2, 3};
List<int> set2 = new List<int>() {4, 5, 6};

我想要的是这段代码的简写:

List<int> fullSet = new List<int>();
fullSet.AddRange(set1);
fullSet.AddRange(set2);

提前致谢!

【问题讨论】:

  • 您说的是 .NET 2/3 还是 3.5?这里的大多数解决方案仅适用于 3.5。

标签: c# list syntax initialization


【解决方案1】:

允许重复元素(如您的示例):

List<int> fullSet = set1.Concat(set2).ToList();

这可以推广到更多列表,即...Concat(set3).Concat(set4)。如果要删除重复元素(出现在两个列表中的那些项目):

List<int> fullSet = set1.Union(set2).ToList();

【讨论】:

    【解决方案2】:
            static void Main(string[] args)
            {
                List<int> set1 = new List<int>() { 1, 2, 3 };
                List<int> set2 = new List<int>() { 4, 5, 6 };
    
                List<int> set3 = new List<int>(Combine(set1, set2));
            }
    
            private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2)
            {
                foreach (var item in list1)
                {
                    yield return item;
                }
    
                foreach (var item in list2)
                {
                    yield return item;
                }
            }
    

    【讨论】:

    • 我不知道为什么当我第一次回答这个问题时,我认为 OP 正在寻找 2.0 解决方案......不知道我从哪里得到的......
    【解决方案3】:
    var fullSet = set1.Union(set2); // returns IEnumerable<int>
    

    如果你想要 List 而不是 IEnumerable 你可以这样做:

    List<int> fullSet = new List<int>(set1.Union(set2));
    

    【讨论】:

      【解决方案4】:
      List<int> fullSet = new List<int>(set1.Union(set2));
      

      可能会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-05
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-22
        • 2020-07-03
        相关资源
        最近更新 更多