簡體   English   中英

如何使用LINQ C#

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM