简体   繁体   中英

Linq query to compare 2 List<string> for distinct matches

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" };

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"

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,具体取决于字符串是否匹配,然后您只需对结果求和即可。

Another solution would be to use an intersect. Like this:

    private class User
    {
        public string UserName { get; set; }
    }

    [TestMethod]
    public void TwoListsWithSameUsersReturnCorrectCountOfEquality()
    {
        var user1 = new User { UserName = "Tim" };
        var user2 = new User { UserName = "Bob" };
        var user3 = new User { UserName = "Brian" };
        var user4 = new User { UserName = "Paul" };

        IList<string> List1 = new List<string> 
                { user1.UserName, user2.UserName, user3.UserName, user4.UserName };

        IList<string> List2 = new List<string> { "Tim", "Bob", "Brian", "Paul" };

        var sameUser = List1.Distinct().Intersect(List2.Distinct());

        Assert.AreEqual(4, sameUser.Count());
    }

Note that the comparison is case sensitive. So tim will result in a count of 4 equal named users.

Update This will indeed not take the order of the lists into account. This was not in the original question and I missed the comments before posting this. Without the order requirement this answer is still suitable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM