计数字符串出现在列表中,并将其连同出现的时间一起复制到强类型列表中- c#

本文关键字:列表 一起 时间 复制 强类型 字符串 数字 | 更新日期: 2023-09-27 17:53:05

我有一个包含不同单词的字符串列表,大多数单词都是重复的。现在我想从list中复制所有的字符串并保存到强类型的list中,其中包含string本身并且它不会出现在list中。我需要使用LINQ

模型类

 public class WordCount
{
    public WordCount()
    { }
    public int ID { get; set; }
    public string word { get; set; }
    public int counter { get; set; }
}

我的当前列表

 private List<string> _WordContent = new List<string>();

新增强类型列表?????????

 public void CountWordInWebSiteContent()
    {
        var counts = _WordContent
                    .GroupBy(w => w)
                    .Select(g => new { Word = g.Key, Count = g.Count() })
                    .ToList();

        List<WordCount> myWordList = new List<WordCount>();

        var a = "d";
    }

计数字符串出现在列表中,并将其连同出现的时间一起复制到强类型列表中- c#

您可以在投影分组结果时创建WordCount的对象:

下面是使用Lambda表达式的语法:

.Select((g,index) => new WordCount
                         { 
                           word = g.Key,
                           counter = g.Count(),
                           ID =index 
        }).ToList();

使用查询表达式语法

int Id=1;
var counts  = from word in _WordContent
              group word by word into g 
              select new WordCount
                         { 
                            ID= Id++,
                            word = g.Key,
                            counter = g.Count() 
                         };

非常感谢Ehsan

完整答案如下;

 myWordList= (from words in _WordContent
                    group words by words into grouped
                    select grouped).Select((g,index) => new WordCount
                     { 
                       word = g.Key,
                       counter = g.Count(),
                       ID =index 
                    }).ToList();