Linq查询以比较2 List< string>用于不同的比赛 [英] Linq query to compare 2 List<string> for distinct matches
问题描述
我是Linq的新手,到处都在搜索此内容,但是找不到答案,因此如果已经提出了借口.我正在寻找一个Linq查询(最好使用lambda/方法语法)来比较2个列表:
I'm new to Linq and have searched for this everywhere but could not find answer so excuse if already asked. I looking for a Linq query (ideally using the lambda/ method syntax) to compare 2 Lists:
IList<string> List1 = new List<string> { usr.User1, usr.User2, usr.User3, usr.User4 };
IList<string> List2 = new List<string>{ "Tim", "Bob", "Brian", "Paul" };
基本上,我希望只有4种可能的匹配,因此:
Basically I would like there to only be 4 possible matches, so if:
usr.User1 == "Tim",
usr.User2 == "Bob",
usr.User3 == "Brian",
usr.User4 == "Paul"
理想情况下,我希望它返回一个0到4之间的整数,因此,如果以上所有匹配均成功,则它将返回4,如果没有匹配成功,则返回0,等等.非常感谢.
I would ideally like it to return an int with a value from 0-4, so if all of the matches above were successful then it would return 4, if no matches successful then returns 0 etc. Many thanks.
推荐答案
List1.Zip(List2, (item1, item2) => item1 == item2 ? 1 : 0).Sum();
Zip()中定义的函数将返回1或0,具体取决于字符串是否匹配,然后您只需对结果求和(Sum())即可.
The function defined in Zip() will return 1 or 0, depending on whether or not the strings match, then you simply Sum() the results.
这篇关于Linq查询以比较2 List< string>用于不同的比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!