I have the following situation, I have a function which returns a List<object
, because the object can be 2 different types Class1
or Class2
, but never mixed. I use this List for a lot of things, but at some point I need a list with names of the objects: List<string>
.
I know how to do this in a for loop, but I would like to know if there is a neat linq/lambda trick for this. Since it simplifies the code.
// An extreme simplified version of my code
List<object> result = this.ProcesInput(input, useFullProces);
List<string> resultNames;
// The following ideas didn't work.
if (useFullProces)
{
resultNames = result.Select(x as Class2 => x.ID.toString()).ToList();
resultNames = result.Select(x => (Class2)x.ID.toString()).ToList();
}
else
{
resultNames = result.Select(x as Class1 => x.name).ToList();
}
Also I know this can be considered dangerous code, but in my situation the type of the returned object is defined by the useFullProces
boolean and will therefore work.
I suspect you just want:
List<string> names = useFullProcess
? result.Cast<Class2>().Select(x => x.ID.ToString()).ToList()
: result.Cast<Class1>().Select(x => x.Name).ToList();
You can use a cast within your Select
, but it's not as clear IMO:
List<string> names = useFullProcess
? result.Select(x => ((Class2) x).ID.ToString()).ToList()
: result.Select(x => ((Class1) x).Name).ToList();
See more on this question at Stackoverflow