Programing

목록에 중복 된 값이있는 목록을 찾는 방법

lottogame 2020. 12. 10. 08:23
반응형

목록에 중복 된 값이있는 목록을 찾는 방법


이 질문에 이미 답변이 있습니다.

List<string>중복 값이 있는지 여부를 찾는 방법 은 무엇입니까?

아래 코드로 시도했습니다. 달성하는 가장 좋은 방법이 있습니까?

var lstNames = new List<string> { "A", "B", "A" };

if (lstNames.Distinct().Count() != lstNames.Count())
{
    Console.WriteLine("List contains duplicate values.");
}

사용 GroupBy하고 Any좋아요;

lstNames.GroupBy(n => n).Any(c => c.Count() > 1);

GroupBy 방법;

지정된 키 선택기 기능에 따라 시퀀스의 요소를 그룹화하고 지정된 기능을 사용하여 각 그룹의 요소를 투영합니다.

Any메서드, 반환 boolean;

시퀀스의 요소가 존재하는지 또는 조건을 충족하는지 여부를 판별합니다.


이 작업을 수행하는 가장 효율적인 방법을 찾고 있다면

var lstNames = new List<string> { "A", "B", "A" };
var hashset = new HashSet<string>();
foreach(var name in lstNames)
{
    if (!hashset.Add(name))
    {
        Console.WriteLine("List contains duplicate values.");
        break;
    }
}

첫 번째 중복을 찾는 즉시 중지 됩니다 . 여러 곳에서 사용할 경우이를 메서드 (또는 확장 메서드)로 래핑 할 수 있습니다.


해시 기술을 기반으로 한 답변의 일반화되고 압축 된 확장 버전 :

public static bool AreAnyDuplicates<T>(this IEnumerable<T> list)
{
    var hashset = new HashSet<T>();
    return list.Any(e => !hashset.Add(e));
}

var duplicateExists = lstNames.GroupBy(n => n).Any(g => g.Count() > 1);

 class Program
{
    static void Main(string[] args)
    {
        var listFruits = new List<string> { "Apple", "Banana", "Apple", "Mango" };
        if (FindDuplicates(listFruits)) { WriteLine($"Yes we find duplicate"); };
        ReadLine();
    }
    public static bool FindDuplicates(List<string> array)
    {
        var dict = new Dictionary<string, int>();
        foreach (var value in array)
        {
            if (dict.ContainsKey(value))
                dict[value]++;
            else
                dict[value] = 1;
        }
        foreach (var pair in dict)
        {
            if (pair.Value > 1)
                return true;
            else
                return false;
        }
        return false;
    }
}  

참고 URL : https://stackoverflow.com/questions/14363424/how-to-find-list-has-duplicate-values-in-liststring

반응형