将IGrouping转换为IList<;类>;

本文关键字:lt gt IList IGrouping 转换 | 更新日期: 2023-09-27 18:20:58

我想从IGrouping查询中获取结果并将其放入列表中。

我试着这样做如下:

实体类

public class WordRank
{
    public string Word { get; set; }
    public string WordScore { get; set; }
}

方法

     public void DisplayArticles()
    {
        var articles = this.articleRepository.TextMinerFindBy(this.view.Client, this.view.Brand, this.view.Project, this.view.Term, this.view.Channel, this.view.Begin, this.view.End, this.view.OnlyCategorized, this.view.UniquePosts);
        string snippets = string.Empty;
        foreach (var article in articles)
        {
            snippets = snippets + " " + article.Snippet;
        }
        Regex wordCountPattern = new Regex(@"[.,;:!?""'s-]");
        string snippetCollection = wordCountPattern.Replace(snippets, " ");
        var words = snippetCollection.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        var groups = words.GroupBy(w => w);

        foreach (var item in groups)
        {
            this.view.Words.Add(item);
        }
    }

但无法将项目分配给IList。有人能给我点光吗?

感谢

将IGrouping转换为IList<;类>;

编辑:好吧,现在我们知道你要做什么了(见评论):

foreach (var group in groups)
{
    this.view.Words.Add(new WordRank { Word = group.Key,
                                       WordScore = group.Count() });
}

或者,如果您愿意将整个this.view.Words替换为List<WordRank>,请将整个底部位替换为:

this.view.Words = words.GroupBy(w => w)
                       .Select(new WordRank { Word = group.Key,
                                              WordScore = group.Count() })
                       .ToList();