Consider the following code:
public interface ITest
{
public string Id { get; set; }
}
public class MyObject : ITest {
{
public string Id { get; set; }
public string Value { get; set; }
}
public void Run()
{
IList<MyOBject> myObjects = GetMyObjects();
myObjects = GetTestITems(myObjects);
}
public IList<ITest> GetTestItems(IList<ITest> items)
{
//run some logic
return items;
}
The above code will fail twice. The first time is when it tries to cast IList<MyObject>
to IList<ITest>
and then when it tries to cast back to IList<MyObject>
. However, if I change the code to following, then it works:
public void Run()
{
IList<MyOBject> myObjects = GetMyObjects();
var myTests = new List<ITest>();
foreach(var o in myObjects) {
myTests.Add(o);
}
var result = GetTestITems(myTests);
myObjects = new List<MyObject>();
foreach(var r in result) {
myObjects.Add(r);
}
}
Is there a way I can achieve this without having to loop twice like this? Maybe a linq way or something in form of casting? I have tried direct casts but it failed on both instances, going to ITest and back to MyObject.