简体   繁体   English

如何在一个列表中合并两个列表而不采取联合或加入 C # 而不重复?

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

italic Problem: We have the Student class with a single field Name (string).Build a function that takes as input two student lists and returns a single list that contains elements of two input lists, excluding those with duplicate names.斜体问题:我们有学生 class 与单个字段名称(字符串)。构建一个 function 作为输入两个学生列表并返回一个包含两个输入列表元素的单个列表,不包括具有重复名称的元素。 italic Here is my code:斜体这是我的代码:

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


            }
        }
    }
}     

If you want to remove duplicates I suggest using set , eg HashSet<string> :如果要删除重复项,我建议使用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);

Or if using UnionWith is cheating :或者如果使用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);   

Finally, if everything but ListResult is prohibited (disclamer: List<T> is not very good choice for Contains ):最后,如果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);

you can easily turn foreach loop into for one:您可以轻松地将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);
   }

You can use the AddRange method to combine the two lists then use Distinct to get rid of the duplicates.您可以使用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));

prints:印刷:

A
B
C
D

You can also do the following.. this keeps the original lists unmodified.您还可以执行以下操作.. 这会使原始列表保持不变。

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

Adding to the HashSet answer by Dmitry, assuming that you are only not allowed to use Join and Union I think it another alternative is to use the .Distinct() method in System.Linq .添加到 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);    
        }
    }
}

Albeit, this answer is going to be slower compared to using HashSet.尽管与使用 HashSet 相比,这个答案会慢一些。

Using Union seems to be the best option here, but if you cant:在这里使用Union似乎是最好的选择,但如果你不能:

ListA.Concat(ListB).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM