正确实现在longlistselector groupheader中使用的IGrouping

时间:2016-01-07 14:37:06

标签: linq windows-phone-8 longlistselector

我有一个ObservableCollection,如下所示 -

    private ObservableCollection<KeyedList<int, Anime>> _grp;
    public ObservableCollection<KeyedList<int, Anime>> GroupedAnimeByGenre
    {
        get
        {
            return _grp;

        }
        set
        {
            _grp = value;
            RaisePropertyChanged("GroupedAnimeByGenre");
        }
    }

我使用它来填充LongListSelector并进行分组。 KeyedList实现如下 -

public class KeyedList<TKey, TItem> : List<TItem>
{
    public TKey Key { protected set; get; }

    public KeyedList(TKey key, IEnumerable<TItem> items)
        : base(items)
    {
        Key = key;
    }

    public KeyedList(IGrouping<TKey, TItem> grouping)
        : base(grouping)
    {
        Key = grouping.Key;
    }
}

我有以下代码来提供ObservableCollection。请记住,AnimeList2是一个临时的集合。

 var groupFinale = AnimeList2.GroupBy(txt => txt.id).Where(grouping => grouping.Count() > 1).ToObservableCollection();

 GroupedAnimeByGenre = groupFinale ;

但是我无法使用GroupedAnimeByGenre转换/使用groupFinale。我缺少扩展方法部分,因为我不太清楚语法。请帮忙

1 个答案:

答案 0 :(得分:0)

如果您移除了ToObservableCollection()来电并只接受该部分

var groupFinale = AnimeList2.GroupBy(txt => txt.id).Where(grouping => grouping.Count() > 1);

您会看到groupFinale的类型为IEnumerable<IGrouping<int, Anime>>。因此,应用ToObservableCollection()将导致ObservableCollection<IGrouping<int, Anime>>。但是,GroupedAnimeByGenre的类型为ObservableCollection<KeyedList<int, Anime>>。因此,您需要将IEnumerable<IGrouping<int, Anime>>转换为IEnumerable<KeyedList<int, Anime>>,其中LINQ由Select方法执行。

很快,你可以使用这样的东西

var groupFinale = AnimeList2
    .GroupBy(txt => txt.id)
    .Where(grouping => grouping.Count() > 1)
    .Select(grouping => new KeyedList<int, Anime>(grouping))
    .ToObservableCollection();

您可以通过提供一个扩展方法(类似于提供ToArray() / ToList()的BCL)来更轻松地进行此类转换,这将允许跳过类似这样的类型参数

public static class KeyedList
{
    public static KeyedList<TKey, TItem> ToKeyedList<TKey, TItem>(this IGrouping<TKey, TItem> source)
    {
        return new KeyedList<TKey, TItem>(source); 
    }
}

然后你可以简单地使用

var groupFinale = AnimeList2
    .GroupBy(txt => txt.id)
    .Where(grouping => grouping.Count() > 1)
    .Select(grouping => grouping.ToKeyedList())
    .ToObservableCollection();