给定一个字符串列表,我想创建一个以下对象的列表
class LineInfo
{
public string line { get; set; }
public bool isSearchMatch { get; set; }
public int searchMatchNumber { get; set; }
}
我希望searchMatchNumber的第一场比赛为1,第二场比赛为2,等等。否则可以为零
我这样设置
IEnumerable<string> allLines; //pulled in from somewhere
IEnumerable<LineInfo> logInfoLines = allLines.Select((l, i) => new LineInfo
{
line = l,
isSearchMatch = l.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0
});
如何设置searchMatchNumber?
答案 0 :(得分:0)
LINQ查询不应该导致这样的副作用。如果您添加OrderBy
,则会获得不同的结果。我不会为此使用LINQ,你可以提供一种方法:
class LineInfo
{
public string line { get; set; }
public bool isSearchMatch { get; set; }
public int searchMatchNumber { get; set; }
public static IEnumerable<LineInfo> GetSearchResult(IEnumerable<string> allLines, string search)
{
int matchCounter = 0;
var lineInfoList = new List<LineInfo>();
foreach (string line in allLines)
{
bool isMatch = line.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0;
var li = new LineInfo
{
line = line,
isSearchMatch = isMatch,
searchMatchNumber = isMatch ? ++matchCounter : -1 // or whatever
};
lineInfoList.Add(li);
}
return lineInfoList;
}
}