문제

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);

미리 감사드립니다!

도움이 되었습니까?

해결책

중복 요소를 허용하려면 (예에서와 같이) :

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

이것은 더 많은 목록에 대해 일반화 될 수 있습니다 ...Concat(set3).Concat(set4). 중복 요소 (두 목록에 나타나는 항목)를 제거하려면 :

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

다른 팁

        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>

목록을 원한다면u003Cint> ienumerable 대신u003Cint> 당신은 할 수 있습니다 :

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

작동 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top