How do you concatenate Lists in C#?

前端 未结 6 1967
闹比i
闹比i 2020-12-23 13:09

If I have:

List myList1;
List myList2;

myList1 = getMeAList();
// Checked myList1, it contains 4 strings

myList2 = getMeAnother         


        
6条回答
  •  清酒与你
    2020-12-23 13:27

    I know this is old but I came upon this post quickly thinking Concat would be my answer. Union worked great for me. Note, it returns only unique values but knowing that I was getting unique values anyway this solution worked for me.

    namespace TestProject
    {
        public partial class Form1 :Form
        {
            public Form1()
            {
                InitializeComponent();
    
                List FirstList = new List();
                FirstList.Add("1234");
                FirstList.Add("4567");
    
                // In my code, I know I would not have this here but I put it in as a demonstration that it will not be in the secondList twice
                FirstList.Add("Three");  
    
                List secondList = GetList(FirstList);            
                foreach (string item in secondList)
                    Console.WriteLine(item);
            }
    
            private List GetList(List SortBy)
            {
                List list = new List();
                list.Add("One");
                list.Add("Two");
                list.Add("Three");
    
                list = list.Union(SortBy).ToList();
    
                return list;
            }
        }
    }
    

    The output is:

    One
    Two
    Three
    1234
    4567
    

提交回复
热议问题