C# 如何保留字符串[]中的重复项从列表中排除单词并将其打印出来
我有一个C# 如何保留字符串[]中的重复项从列表中排除单词并将其打印出来,c#,arrays,string,linq,C#,Arrays,String,Linq,我有一个字符串,我想保留最重复的单词。还有我想从字符串中排除的字符串列表。我只能在通过字符串和列表后返回bool,这将得到我想要的结果。但是,如何从该方法而不是bool返回字符串?我尝试了以下方法: //Fields private String textOnBook = "alis and joe went to the store to buy fish and salad salad is joe favorite food"; private List<St
字符串
,我想保留最重复的单词。还有我想从字符串中排除的字符串列表。我只能在通过字符串和列表后返回bool
,这将得到我想要的结果。但是,如何从该方法而不是bool返回字符串
?我尝试了以下方法:
//Fields
private String textOnBook = "alis and joe went to the store to buy fish and salad salad is joe favorite food";
private List<String> excludeFromText = new List<string>() {"and", "he", "the", "to", "is"};
public List<String> MostUsedWords(String textOnBook, List<String> excludeFromText)
{
var word = textOnBook.Split(' ');
for (int i = 0; i < word.Length; i++)
{
var result = excludeFromText.Remove(word[i]);
Console.WriteLine(result);
}
return null;
}
//字段
private String textOnBook=“alis和joe去商店买鱼和沙拉沙拉沙拉是joe最喜欢的食物”;
private List excludeFromText=new List(){“and”、“he”、“the”、“to”、“is”};
公共列表MOSTUSEDWORD(字符串textOnBook,列表excludeFromText)
{
var word=textOnBook.Split(“”);
for(int i=0;i
非常感谢你的帮助,和平 我建议如下(输出joe
和sala
)
两个GroupBy
s允许您对单词进行分组,然后计算每个单词的实例数OrderByDescending
和First
允许您查找最常用的单词<代码>选择多个
然后提取这些单词,并且除外
排除要排除的特定单词(例如和
)(其中
用于处理边缘大小写,其中文本本
为空白字符串)string.Join
用于显示列表的内容
使用系统;
使用System.Linq;
使用System.Collections.Generic;
公共课程
{
private static List excludeFromText=new List(){“and”、“he”、“the”、“to”、“is”};
private static String textOnBook=“alis和joe去商店买鱼和沙拉沙拉沙拉是joe最喜欢的食物”;
公共静态void Main()
{
Console.WriteLine(string.Join(“,”,MostUsedWords(textOnBook,excludeFromText));
}
公共静态列表MostUsedWords(字符串textOnBook,列表excludeFromText)
{
var words=textOnBook.Split(“”);
返回words.GroupBy(z=>z)
.GroupBy(z=>z.Count())
.OrderByDescending(z=>z.Key)
.First()
.SelectMany(z=>z)
.其中(z=>z.长度>0)
.除外(不包括原文)
.ToList();
}
}
非常感谢,我很困惑!你是如何得出使用Lambda表达式的结论的,它是有效的?@Jacman我想我倾向于用集合的方式来形象化问题,因此LINQ在这里似乎是合适的。
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
private static List<String> excludeFromText = new List<string>() {"and", "he", "the", "to", "is"};
private static String textOnBook = "alis and joe went to the store to buy fish and salad salad is joe favorite food";
public static void Main()
{
Console.WriteLine(string.Join(",", MostUsedWords(textOnBook, excludeFromText)));
}
public static List<String> MostUsedWords(String textOnBook, List<String> excludeFromText)
{
var words = textOnBook.Split(' ');
return words.GroupBy(z => z)
.GroupBy(z => z.Count())
.OrderByDescending(z => z.Key)
.First()
.SelectMany(z => z)
.Where(z => z.Length > 0)
.Except(excludeFromText)
.ToList();
}
}