[英]How to use LINQ C#
I have a ConcurrentDictionary<string, int> word = new ConcurrentDictionary<string, int>();
我有一个
ConcurrentDictionary<string, int> word = new ConcurrentDictionary<string, int>();
And i have List for files: static List<string> file = new List<string>(60);
我有文件列表:
static List<string> file = new List<string>(60);
Before, I used to use this path to write file information string line; 以前,我曾经使用此路径写文件信息字符串行;
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);
}
}
In this case the right to use a LINQ? 在这种情况下有权使用LINQ? I try this way,but it't not right:
我尝试这种方式,但这不正确:
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());
Let me try doing some reverse engineering . 让我尝试做一些逆向工程 。 It seems, that you have several files (in the
file
list) organized like this: 看来,您有几个文件(在
file
列表中)组织如下:
some words
several new words
nothing new
and you want some kind of a dictionary as a result 而你想要某种字典
{"some", 1} // 1: "some' appears just once
{"words", 2} // 2: 'words' appears twice
{"several", 1}
{"new", 2}
{"nothing", 1}
...
where Key
is a word itself, and Value
is its frequency. 其中
Key
是单词本身,而Value
是其频率。 If it's your case and if you want to implement it with a help of Linq while using parallel processes , try using PLinq ; 如果您是这种情况,并且希望在使用并行进程时在Linq的帮助下实现它,请尝试使用PLinq;。 something like this:
像这样的东西:
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());
Please, notice that you'll get just Dictionary
, not ConcurrentDictionary
. 请注意,您只会得到
Dictionary
,而不是ConcurrentDictionary
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.