Search code examples
c#linqcollectionsprojection

C#: projection - accessing a given string property in a collection of objects in the same way as a List<string>


a quick projection question. I have a collection of objects (unchangeditems) in a test method, and would like to ensure they match my 'expected' elements. As shown you could do it by element, but this isn't ideal. I'm sure its possible to use projection to get down to the string variable (LMAA_CODE - don't ask about the capitals!) along the lines of the bottom line below. I'd appreciate a hand.

Thanks!

// Works but not very elegant
            Assert.AreEqual(result.unchangedItems[0].LMAA_CODE,expectedunchangedItems[0]);
            Assert.AreEqual(result.unchangedItems[1].LMAA_CODE,expectedunchangedItems[1]);
            Assert.AreEqual(result.unchangedItems[2].LMAA_CODE,expectedunchangedItems[2]);
            Assert.AreEqual(result.unchangedItems[3].LMAA_CODE,expectedunchangedItems[3]);

        // ?Can something like this be done?  eg result.unchangedItems => result.unchangedItems.LMAA_CODE
        Assert.IsTrue(Enumerable.SequenceEqual(result.unchangedItems.LMAA_CODE, expectedunchangedItems));

Solution

  • You were almost there already, just added a projection to LMAA_CODE:

     Assert.IsTrue(Enumerable.SequenceEqual(result.unchangedItems.Select( x=> x.LMAA_CODE), 
                                            expectedunchangedItems));