[英]How to use LINQ C#
我有一个ConcurrentDictionary<string, int> word = new ConcurrentDictionary<string, int>();
我有文件列表: static List<string> file = new List<string>(60);
以前,我曾经使用此路径写文件信息字符串行;
string[] lines;
string[] linesUnos;
string[] sp = { " " };
int i = (int)obj;
StreamReader reder = new StreamReader(file[i]);
line = " ";
while (!reder.EndOfStream)
{
line = reder.ReadLine().ToLower();
lines = line.Split(sp, StringSplitOptions.RemoveEmptyEntries);
foreach (var w in lines )
{
word.AddOrUpdate(w, 1, (key, oldValue) => oldValue + 1);
}
}
在这种情况下有权使用LINQ? 我尝试这种方式,但这不正确:
IEnumerable<string> f, w;
line = reder.ReadLine().ToLower();
f = from lin in line.Split(sp, StringSplitOptions.RemoveEmptyEntries) select lin;
word = line.ToDictionary(s => s.Key, s => s.Count());
让我尝试做一些逆向工程 。 看来,您有几个文件(在file
列表中)组织如下:
some words
several new words
nothing new
而你想要某种字典
{"some", 1} // 1: "some' appears just once
{"words", 2} // 2: 'words' appears twice
{"several", 1}
{"new", 2}
{"nothing", 1}
...
其中Key
是单词本身,而Value
是其频率。 如果您是这种情况,并且希望在使用并行进程时在Linq的帮助下实现它,请尝试使用PLinq;。 像这样的东西:
Dictionary<string, int> dict = file
.AsParallel() // Doing in parallel
.SelectMany(file => File.ReadLines(files)) // Read all lines of all files
.SelectMany(line => line.Split( // Split each line into words
new char[] {' '},
StringSplitOptions.RemoveEmptyEntries))
// You may want to process words here, e.g. get rid of "stop words"
.GroupBy(w => w) // Group by each word
.ToDictionary(chunk => chunk.Key, chunk => chunk.Count());
请注意,您只会得到Dictionary
,而不是ConcurrentDictionary
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.