【发布时间】:2021-11-23 21:30:19
【问题描述】:
我有这样的课程:
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
}
那么我如何在列表中的第一个和第三个项目上将 wordIsFound 设置为 1(与 wordSearch 匹配的项目?
【问题讨论】:
-
这个逻辑没有意义,如果一个单词有值,为什么要“保存”到变量中而不是检查它?
-
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;