Sintassi per inizializzare un elenco < T > con Elenco esistente < T > oggetti
-
05-07-2019 - |
Domanda
è possibile inizializzare un Elenco con altri Elenco in C #? Di 'che ho questi in elenchi:
List<int> set1 = new List<int>() {1, 2, 3};
List<int> set2 = new List<int>() {4, 5, 6};
Quello che vorrei avere è una scorciatoia per questo codice:
List<int> fullSet = new List<int>();
fullSet.AddRange(set1);
fullSet.AddRange(set2);
Grazie in anticipo!
Soluzione
Per consentire elementi duplicati (come nel tuo esempio):
List<int> fullSet = set1.Concat(set2).ToList();
Questo può essere generalizzato per più elenchi, ad esempio ... Concat (set3) .Concat (set4)
. Se desideri rimuovere elementi duplicati (quegli elementi che compaiono in entrambi gli elenchi):
List<int> fullSet = set1.Union(set2).ToList();
Altri suggerimenti
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;
}
}
var fullSet = set1.Union(set2); // returns IEnumerable<int>
Se vuoi Elenco < int > invece di IEnumerable < int > potresti fare:
List<int> fullSet = new List<int>(set1.Union(set2));
List<int> fullSet = new List<int>(set1.Union(set2));
potrebbe funzionare.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow