Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq Char arrays Except() - Weird behavior

Tags:

c#

linq

I am at a loss to understand why this Test would fail with Message "Assert.AreEqual failed. Expected:<2>. Actual:<1>."

        [TestMethod]
        public void Test()
        {
            char[] a1 = "abc".ToCharArray();
            char[] a2 = {'a', 'b', 'c', ' ', ' '};

            Assert.AreEqual(2, a2.Except(a1).Count());
        }

but the following would pass:

        [TestMethod]
        public void Test()
        {
            char[] a1 = "abc".ToCharArray();
            char[] a2 = {'a', 'b', 'c', ' ', 'd', ' '};

            Assert.AreEqual(2, a2.Except(a1).Count());
        }
like image 620
Raghu Avatar asked May 04 '12 13:05

Raghu


3 Answers

Except gives you a SET which means it does not return duplicates.

See Except documentation

like image 50
jorgehmv Avatar answered Oct 09 '22 12:10

jorgehmv


The Except function returns the set difference of the two sequences - not the difference.

The space character only gets returned once.

like image 22
Anders Marzi Tornblad Avatar answered Oct 09 '22 11:10

Anders Marzi Tornblad


because except finds difference of two sequences

http://msdn.microsoft.com/ru-ru/library/system.linq.enumerable.except.aspx

maybe you need something like this

var c=a2.Where(a=>a1.Contains(a)==false).Count();
like image 36
user1208484 Avatar answered Oct 09 '22 13:10

user1208484