Programing

linq 결과를 HashSet 또는 HashedSet로 변환하는 방법

crosscheck 2020. 5. 16. 11:09
반응형

linq 결과를 HashSet 또는 HashedSet로 변환하는 방법


ISet 인 클래스에 속성이 있습니다. linq 쿼리 결과를 해당 속성으로 가져 오려고하지만 그렇게하는 방법을 알 수 없습니다.

기본적으로 이것의 마지막 부분을 찾으십시오.

ISet<T> foo = new HashedSet<T>();
foo = (from x in bar.Items select x).SOMETHING;

또한 이것을 할 수 있습니다 :

HashSet<T> foo = new HashSet<T>();
foo = (from x in bar.Items select x).SOMETHING;

나는 이것을하는 내장 된 것이 없다고 생각 하지만 확장 방법을 작성하는 것은 정말 쉽습니다.

public static class Extensions
{
    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source,
        IEqualityComparer<T> comparer = null)
    {
        return new HashSet<T>(source, comparer);
    }
}

T명시 적으로 유형을 표현할 수 없으므로 확장 메소드 (또는 적어도 어떤 형태의 일반적인 메소드)를 원합니다 .

var query = from i in Enumerable.Range(0, 10)
            select new { i, j = i + 1 };
var resultSet = query.ToHashSet();

HashSet<T>생성자에 대한 명시 적 호출로는 그렇게 할 수 없습니다 . 우리는 일반적인 방법으로 타입을 추론하고 있습니다.

이제 이름을 지정 하고 반환 있습니다. 하지만 구체적인 유형을 고수 합니다. 이는 표준 LINQ 연산자 ( , )와 일치하며 향후 확장 (예 :)을 허용합니다 . 사용할 비교를 지정하여 과부하를 제공 할 수도 있습니다.ToSetISet<T>ToHashSetToDictionaryToListToSortedSet


IEnumerable을 HashSet의 생성자로 전달하십시오.

HashSet<T> foo = new HashSet<T>(from x in bar.Items select x);

이 기능에 대한 확장 방법으로 추가되었습니다 IEnumerable<TSource>.NET 프레임 워크 4.7.2 :


@Joel이 말했듯이 열거 형을 전달할 수 있습니다. 확장 방법을 원한다면 다음을 수행 할 수 있습니다.

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
    return new HashSet<T>(items);
}

세트에 대한 읽기 전용 액세스가 필요하고 소스가 메소드의 매개 변수 인 경우

public static ISet<T> EnsureSet<T>(this IEnumerable<T> source)
{
    ISet<T> result = source as ISet<T>;
    if (result != null)
        return result;
    return new HashSet<T>(source);
}

그 이유는 사용자가 ISet이미 메소드를 호출하여 사본을 작성할 필요가 없기 때문입니다.


닷넷 프레임 워크와 .NET의 핵심에 확장 방법 빌드로 변환하기위한이 IEnumerableA를 HashSet: https://docs.microsoft.com/en-us/dotnet/api/?term=ToHashSet

public static System.Collections.Generic.HashSet<TSource> ToHashSet<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

아직 .NET 표준 라이브러리에서 사용할 수없는 것 같습니다 (작성 당시). 그런 다음이 확장 방법을 사용합니다.

    [Obsolete("In the .NET framework and in NET core this method is available, " +
              "however can't use it in .NET standard yet. When it's added, please remove this method")]
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer = null) => new HashSet<T>(source, comparer);

꽤 간단합니다 :)

var foo = new HashSet<T>(from x in bar.Items select x);

그리고 예 T는 OP에 의해 지정된 유형입니다 :)


존의 대답은 완벽합니다. 유일한주의 사항은 NHibernate의 HashedSet을 사용하여 결과를 컬렉션으로 변환해야한다는 것입니다. 이를위한 최적의 방법이 있습니까?

ISet<string> bla = new HashedSet<string>((from b in strings select b).ToArray()); 

또는

ISet<string> bla = new HashedSet<string>((from b in strings select b).ToList()); 

아니면 다른 것을 놓치고 있습니까?


편집 : 이것은 내가 끝낸 일입니다.

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    return new HashSet<T>(source);
}

public static HashedSet<T> ToHashedSet<T>(this IEnumerable<T> source)
{
    return new HashedSet<T>(source.ToHashSet());
}

Rather than the simple conversion of IEnumerable to a HashSet, it is often convenient to convert a property of another object into a HashSet. You could write this as:

var set = myObject.Select(o => o.Name).ToHashSet();

but, my preference would be to use selectors:

var set = myObject.ToHashSet(o => o.Name);

They do the same thing, and the the second is obviously shorter, but I find the idiom fits my brains better (I think of it as being like ToDictionary).

Here's the extension method to use, with support for custom comparers as a bonus.

public static HashSet<TKey> ToHashSet<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> selector,
    IEqualityComparer<TKey> comparer = null)
{
    return new HashSet<TKey>(source.Select(selector), comparer);
}

참고URL : https://stackoverflow.com/questions/3471899/how-to-convert-linq-results-to-hashset-or-hashedset

반응형