Jak połączyć listy w C#?

Jeśli mam:

List<string> myList1;
List<string> myList2;

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

myList2 = getMeAnotherList();
// Checked myList2, it contains 6 strings

myList1.Concat(myList2);
// Checked mylist1, it contains 4 strings... why?

Uruchomiłem kod podobny do tego w Visual Studio 2008 i ustawiłem punkty przerwania po każdym wykonaniu. Po myList1 = getMeAList();, myList1 zawiera cztery struny, i nacisnąłem przycisk plus, aby upewnić się, że nie są wszystkie null.

Po myList2 = getMeAnotherList();, myList2 zawiera sześć ciągów, i sprawdziłem, czy nie są zerowe... Po myList1.Concat(myList2); myList1 zawierało tylko cztery ciągi. Dlaczego?

Author: luk2302, 2009-06-25

7 answers

Concat zwraca nową sekwencję bez modyfikowania oryginalnej listy . Spróbuj myList1.AddRange(myList2).

 241
Author: John Kugelman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:26

Spróbuj tego:

myList1 = myList1.Concat(myList2).ToList();

Concat Zwraca liczbę IEnumerable, czyli dwie połączone listy, nie modyfikuje żadnej z istniejących list. Ponadto, ponieważ zwraca on wartość IEnumerable, jeśli chcesz przypisać ją do zmiennej List, musisz wywołać tolist () na zwracanej wartości IEnumerable.

 76
Author: Jonathan Rupp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-25 04:44:59

Concat nie aktualizuje myList1. Zwraca nową listę zawierającą skonkatenowane myList1 i myList2.

Użycie Zamiast tego.

 10
Author: Jacob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-04 17:54:04
targetList = list1.Concat(list2).ToList();
Chyba działa dobrze. Jak wspomniano wcześniej, Concat zwraca nową sekwencję i podczas konwersji wyniku na Listę, wykonuje zadanie doskonale.
 7
Author: Balasubramani M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-22 03:08:19

Warto również zauważyć, że Concat działa w stałym czasie i w stałej pamięci. Na przykład następujący kod

        long boundary = 60000000;
        for (long i = 0; i < boundary; i++)
        {
            list1.Add(i);
            list2.Add(i);
        }
        var listConcat = list1.Concat(list2);
        var list = listConcat.ToList();
        list1.AddRange(list2);

Podaje następujące wskaźniki czasu/pamięci:

After lists filled mem used: 1048730 KB
concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
 3
Author: Dmitry Andrievsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-22 01:13:16

Wiem, że to stare, ale trafiłem na ten post szybko myśląc, że Concat będzie moją odpowiedzią. Związek pracował dla mnie świetnie. Uwaga, zwraca tylko unikalne wartości, ale wiedząc, że i tak otrzymuję unikalne wartości, To rozwiązanie działało dla mnie.

namespace TestProject
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> FirstList = new List<string>();
            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<string> secondList = GetList(FirstList);            
            foreach (string item in secondList)
                Console.WriteLine(item);
        }

        private List<String> GetList(List<string> SortBy)
        {
            List<string> list = new List<string>();
            list.Add("One");
            list.Add("Two");
            list.Add("Three");

            list = list.Union(SortBy).ToList();

            return list;
        }
    }
}

Wyjście To:

One
Two
Three
1234
4567
 2
Author: Esaith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-28 18:16:32

Spójrz na moją implementację its safe from null lists

 IList<string> all= new List<string>();

            if (letterForm.SecretaryPhone!=null)// first list may be null
               all=all.Concat(letterForm.SecretaryPhone).ToList();

            if (letterForm.EmployeePhone != null)// second list may be null
                all= all.Concat(letterForm.EmployeePhone).ToList(); 

            if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
                all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList(); 
 2
Author: Basheer AL-MOMANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-21 17:46:13