I have 2 classes which have some identical properties. I stock into a list properties from 1st class, and after that, I want to take some needed properties and put them into
var iweil = sil.Select(item=> new InvoiceWithEntryInfo {
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date}).ToList();
Just use Select:
if(sil != null)
{
var iweil = sil.Select(item=>new InvoiceWithEntryInfo()
{
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date
}).ToList();
}
You need a function to convert a T instance to a U instance:
ResultType ConvertMethod(StartType input)
and you need to write this. Then
outputList = inputList.Select(ConvertMethod).ToList();
will apply it to the whole input collection. The conversion function can be a lambda written inline but doesn't need to be (if the function has the right signature, like ConvertMethod then the compiler will convert it correctly to pass to Select).
Your regular C# code and LINQ are not equivalent. In the regular C# you instantiate a new instance of the other class and initialize the properties, whereas you try to cast (well convert) from one to the other; however, since they are not in the same class hierarchy you can't cast, and as you haven't defined a conversion operator, you can't convert (using cast syntax) either.
You either have to define a conversion operator
public static explicit operator InvoiceWithEntryInfo(ServiceInfo item){
return new InvoiceWithEntryInfo {
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date};
}
or a creation method using regular method signature. I'd suggest the latter since the former pretend to be something it's not. It's not a cast and I'd personally like to be able to see that the code creates a new instance based on some input.
var iweilCopy = sil.Select(item => new InvoiceWithEntryInfo()
{
IdWEI = item.Id,
NameWEI = item.Name,
....
}).ToList();