Allan
asked on
Convert To Lamda Expression
Hi Experts.
Need help in converting the usage of the foreach to using a lamda expression to get the list of pets.
//Looking for something like this acutalPets = people............ToList() ;
TIA!
Need help in converting the usage of the foreach to using a lamda expression to get the list of pets.
//Looking for something like this acutalPets = people............ToList()
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
namespace SampleTest
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Location> Locations { get; set; }
}
public class Location
{
public string PetType { get; set; }
public bool HasPets { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//Arrange
List<Person> people = new List<Person>() {
new Person() {FirstName = "FirstName01", LastName = "LastName01",
Locations = new List<Location>() {
new Location() { HasPets = false}
}
},
new Person() {FirstName = "FirstName02", LastName = "LastName02",
Locations = new List<Location>() {
new Location() { PetType = "Dog", HasPets = true }
}
},
new Person() {FirstName = "FirstName03", LastName = "LastName03",
Locations = new List<Location>() {
new Location() {PetType = "Cat", HasPets = true},
new Location() {PetType = "Dog", HasPets = true},
new Location() {PetType = "Axolotl", HasPets = true}
}
},
new Person() {FirstName = "FirstName04", LastName = "LastName04",
Locations = new List<Location>() {
new Location() { PetType = "Cat", HasPets = true },
new Location() { PetType = "Dog", HasPets = true }
}
}
};
List<string> expectedPets = new List<string>() { "Axolotl", "Cat", "Dog" };
//Act
List<string> acutalPets = new List<string>();
foreach (var person in people)
{
foreach (var location in person.Locations)
{
string pet = location.HasPets ? location.PetType : "";
if (pet != string.Empty && !acutalPets.Contains(pet))
acutalPets.Add(pet);
}
}
//Looking for something like this acutalPets = people............ToList();
//Assert -- IsCollectionSame is an Extension method that returns true if both collections have same content
Assert.IsTrue(expectedPets.IsCollectionSame(acutalPets));
}
}
}
TIA!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER