提问人:E.D. 提问时间:11/24/2021 更新时间:11/24/2021 访问量:44
如何在.NET中一次设置所有找到的列表词值?
How to set all found list words values at once in .NET?
问:
我有一个这样的类:
public class cls_words : IEquatable<cls_words>
{
public int indx { get; set; }
public string wordTxt { get; set; }
public int wordIsFound { get; set; }
public override string ToString()
{
return "ID: " + wordIsFound + " Name: " + wordTxt;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
cls_words objAsWord = obj as cls_words;
if (objAsWord == null) return false;
else return Equals(objAsWord);
}
public override int GetHashCode()
{
return wordIsFound;
}
public bool Equals(cls_words other)
{
if (other == null) return false;
return (this.wordIsFound.Equals(other.wordIsFound));
}
}
基本上,类是一个单词,无论它是否在搜索中找到。
因此,我创建了一个这样的类列表:
List<cls_words> wordsIn = new List<cls_words>();
wordsIn.Add(new cls_words { indx= 1, wordTxt = "test", wordIsFound=0 });
wordsIn.Add(new cls_words { indx= 2, wordTxt = "the", wordIsFound=0 });
wordsIn.Add(new cls_words { indx= 3, wordTxt = "test", wordIsFound=0 });
然后,当我搜索列表以查看它是否包含单词时,我想在适当的情况下将所有 wordIsFound 值设置为 1。列表中的某些单词可能相同。
所以像这样
string wordSearch = "test";
if (wordsIn.Exists(x => x.wordTxt == wordSearch)) {
//set all wordIsFound = 1 where word matches wordSearch
}
那么,如何在列表中的第 1 项和第 3 项(与 wordSearch 匹配的项)上将 wordIsFound 设置为 1 ?
答:
0赞
Leandro Bardelli
11/24/2021
#1
string wordSearch = "test";
foreach (cls_words clsword in wordsIn) {
if(cls_word.wordTxt == wordSearch) {
clsword.wordIsFound = 1;
}
}
评论
0赞
E.D.
11/24/2021
这是最好/唯一的方法?在循环中?
0赞
E.D.
11/24/2021
谢谢回复,我认为可能有一种比循环更优雅的方式。例如,行: ''' if (wordsIn.Exists(x => x.wordTxt == wordSearch)) { ''' ....检查所有单词,而不是循环。我知道在幕后它必须循环,但我认为可能有类似的代码进行设置。我想不是。
0赞
Leandro Bardelli
11/24/2021
@E.D. 是的。有一个 ForEach 函数,但在内部执行相同的操作,但性能和易读性较低:S
0赞
Chris
11/24/2021
#2
更简单的方法可能是将 HashSet 与您的类型(甚至只是一个 )。string
HashSet<string> foundWords = new HashSet<string>();
HashSet<string> allWords = new HashSet<string>();
allWords.Add("test");
allWords.Add("apple");
allWords.Add("test"); // This will just "fail silently" if the word is already in the allWords HashSet.
// then to test:
string wordSearch = "test";
if (allWords.Contains(wordSearch)) foundWords.Add(wordSearch);
// you can even loop over your input of a very big string with something like:
string bigString = "this is a long string with many words";
int maxWords = 1000;
string[] allWordsToTest = bigString.Split(' ', maxWords);
foreach (string s in allWordsToTest)
if (allWords.Contains(s)) foundWords.Add(s);
显然,你会想要做一些处理(将单词设置为一致的大小写,在试验之间清空“找到的集”等),但这应该让你开始。
评论
foreach(cls_words cw in wordsIn) cw.wordIsFound = wordsIn.Count(x=> x.wordTxt == cw.wordTxt)-1;
或foreach(cls_words cw in wordsIn) cw.wordIsFound = wordsIn.Count(x=> x.wordTxt .Equals(cw.wordTxt))-1;