我有一个包含不同单词的字符串列表,大多数单词都是重复的。现在我想从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";
}
您可以在投影分组结果时创建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();