을하는 데 도움이
IDictionary<TKey, Summary<TKey>> Summarize<TKey, TValue>(IEnumerable<TValue> values)
{
return values
.ToLookup(val => GetKey(val)) // group values by key
.Union(Enumerable.Repeat(default(TKey), 1).ToLookup(x => GetKey(x)))
.ToDictionary(
group => group.Key,
group => CreateSummary(group)); // summarize each group
}
희망 : 당신은 조합과 솔루션을 원하는 경우처럼
IDictionary<TKey, Summary<TKey>> Summarize<TKey, TValue>(IEnumerable<TValue> values)
{
return values
.ToLookup(val => GetKey(val)) // group values by key
.Select(x => x.Any() ? x : Enumerable.Repeat(default(TKey), 1).ToLookup(x => GetKey(x)))
.ToDictionary(
group => group.Key,
group => CreateSummary(group)); // summarize each group
}
, 당신은 기본 조회 테이블을 만들 같은 논리를 사용할 수 있습니다 GroupBy 또는 ToLookup에서 비어있는 그룹을 가져올 수 없습니다. 아마도 의도적 인 이유가있을 것입니다.
순전히 기능적 방식으로 수행 할 수 있습니까? (변경 가능한 데이터 구조를 사용하지 마십시오.)
이러한 학문적 요구 사항은 재미있을 수 있지만 모든 솔루션은 간단하고 간단한 구현과 비교되어야합니다. 당신이 빈 그룹을 원하는 경우
Dictionary<TKey, Summary<TKey>> result = values
.GroupBy(val => GetKey(val))
.ToDictionary(g => g.Key, g => CreateSummary(g));
TKey x = default(TKey);
if (!result.ContainsKey(x))
{
result[x] = CreateSummary(Enumerable.Empty<TValue>());
}
return result;
지금, 단지 그것을 위해 클래스를 추가 할 수 있습니다
public class EmptyGroup<TKey, TValue> : IGrouping<TKey, TValue>
{
public TKey Key {get;set;}
public IEnumerator GetEnumerator()
{
return GetEnumerator<TValue>();
}
public IEnumerator<TValue> GetEnumerator<TValue>()
{
return Enumerable.Empty<TValue>().GetEnumerator<TValue>();
}
}
은 다음과 같이 사용합니다 :
이
EmptyGroup<TKey, TValue> empty = new EmptyGroup<TKey, TValue>(Key = default<TKey>());
작품처럼 사용할 : 여기에 나를 위해 일한 코드입니다 D – Nate