簡體   English   中英

如何在一個列表中合並兩個列表而不采取聯合或加入 C # 而不重復?

[英]How do I merge two lists in a single list without taking union or join in C # without duplicates?

斜體問題:我們有學生 class 與單個字段名稱(字符串)。構建一個 function 作為輸入兩個學生列表並返回一個包含兩個輸入列表元素的單個列表,不包括具有重復名稱的元素。 斜體這是我的代碼:

using System;
using System.Collections.Generic;

namespace ExerciseGeneric(listA, listB)
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> ListA = new List<string>
      { 
         "James",
         "Jon",
         "Mark",
         "Jey",
         "Sara",
      };

            List<string> ListB = new List<string>
      {
         "Peter",
         "Parker",
         "Bond",
         "Sara"
      };

          

          
            List<string> ListResult = new List<string>();

            foreach (var item in ListA)
            {
                ListResult.Add(item);
            }

            foreach (var item in ListB)
            {
                ListResult.Add(item);
            }
            for (var i = 0; i < ListResult.Count; ++i)
                {
                    for (var j = i + 1; j < ListResult.Count; ++j)
                    {
                        
                        if (ListResult[i] == ListResult[j])
                        {
                            ListResult.Remove(j, 1);
                    }
                    break;
                }

            foreach (var result in ListResult)
            {
                Console.WriteLine("ListResult : " + result);
            }


            }
        }
    }
}     

如果要刪除重復項,我建議使用set ,例如HashSet<string>

   HashSet<string> combined = new HashSet<string>(ListA);

   combined.UnionWith(ListB);

   List<string> ListResult = new List<string>(combined.Count);

   foreach (string item in combined)
     ListResult.Add(item);

或者如果使用UnionWith作弊

   HashSet<string> combined = new HashSet<string>();  

   List<string> ListResult = new List<string>();

   foreach (string item in ListA)
     if (combined.Add(item)) // if item is unique (i.e. added to the set)
       ListResult.Add(item); // we add it into the list as well  

   foreach (string item in ListB)
     if (combined.Add(item))
       ListResult.Add(item);   

最后,如果ListResult的所有內容都被禁止(聲明: List<T>對於Contains來說不是很好的選擇):

   List<string> ListResult = new List<string>();

   foreach (string item in ListA)
     if (!ListResult.Contains(item))
       ListResult.Add(item);

   foreach (string item in ListB)
     if (!ListResult.Contains(item))
       ListResult.Add(item);

您可以輕松地將foreach循環變成for one:

   for (int i = 0; i < ListA.Count; ++i) {
     string item = listA[i];

     if (!ListResult.Contains(item))
       ListResult.Add(item);
   }

   for (int i = 0; i < ListB.Count; ++i) {
     string item = listB[i];

     if (!ListResult.Contains(item))
       ListResult.Add(item);
   }

您可以使用AddRange方法組合兩個列表,然后使用Distinct去除重復項。

List<string> namesA = new List<string>() { "A", "B", "C" };
List<string> namesB = new List<string>() { "D", "A", "B" };

namesA.AddRange(namesB);
List<string> combined = namesA.Distinct().ToList();

combined.ForEach(x => Console.WriteLine(x));

印刷:

A
B
C
D

您還可以執行以下操作.. 這會使原始列表保持不變。

List<string> namesA = new List<string>() { "A", "B", "C" };
List<string> namesB = new List<string>() { "D", "A", "B" };
List<string> combined = new List<string>();

combined.AddRange(namesA);
combined.AddRange(namesB);
combined = combined.Distinct().ToList();

combined.ForEach(x => Console.WriteLine(x));

添加到 Dmitry 的 HashSet 答案,假設您只不允許使用JoinUnion我認為另一種選擇是使用 System.Linq 中的System.Linq .Distinct()方法。

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> ListA = new List<string>
        { 
            "James",
            "Jon",
            "Mark",
            "Jey",
            "Sara",
        };

        List<string> ListB = new List<string>
        {
            "Peter",
            "Parker",
            "Bond",
            "Sara"
        };
        
        List<string> ListResult = new List<string>();

        foreach (var item in ListA)
        {
            ListResult.Add(item);
        }

        foreach (var item in ListB)
        {
            ListResult.Add(item);
        }

        ListResult = ListResult.Distinct()
            .ToList();
        
        foreach(var item in ListResult)
        {
            Console.WriteLine(item);    
        }
    }
}

盡管與使用 HashSet 相比,這個答案會慢一些。

在這里使用Union似乎是最好的選擇,但如果你不能:

ListA.Concat(ListB).Distinct();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM