简体   繁体   English

在 C# 中的另一个列表中搜索列表中的项目

[英]Search item in list in another list in C#

I want to match any string items in the list with substring items in another list, then put substring and repetition in the dictionary without for loop because the substring list contains 24345000 cells.我想将列表中的任何字符串项与另一个列表中的子字符串项进行匹配,然后将子字符串和重复放入字典中而不使用 for 循环,因为子字符串列表包含 24345000 个单元格。

 string[] folders = Directory.GetDirectories(@"..\Raw Data", "*");
 Dictionary<string, int> freq = new Dictionary<string, int>();
 var letters= File.ReadAllLines(@"..\letters.txt").ToList();
 foreach (string folder in folders)
        {
            string name_folder = Path.GetFileName(folder);

            string[] N_F = Directory.GetFiles(@"..\items\" + folder, "*.txt");
            foreach (string f in N_F)
            {
                List<string> s = File.ReadAllText(f).Split(' ').ToList();
                s.RemoveAll(string.IsNullOrWhiteSpace);
                foreach(string t in letters)
                    if(s.Contains(t))
                if (freq.ContainsKey(t))
                        freq[t]++;
                    else
                        freq[t] = 1;
            }
}

You are looking for a way to search count of occurrence of words from a list in another list.您正在寻找一种方法来搜索另一个列表中的列表中的单词出现次数。

// Sample Data 
var letters = new string[] { "Apple", "Orange", "Mango", "Cherry" };
var masterList = new string[] 
                { "Apple", "Tea", "Mango", "Apple", "Wheat", "Mango",
                  "Bread", "Orange", "Mango", "Apple", "Orange", "Mango",
                  "Apple", "Bread", "Mango", "Apple", "Bread", "Tea"
                }; 

You can try:你可以试试:

var freq = words.Select(w => new { Word = w, Count = masterList.Count(m => m == w) })
                              .ToList();

freq will contain: freq将包含:

Word = Apple    Count = 5
Word = Orange    Count = 2
Word = Mango    Count = 5
Word = Cherry    Count = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM