Using LINQ to convert List to List

前端 未结 5 961
长发绾君心
长发绾君心 2020-12-14 05:49

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

相关标签:
5条回答
  • 2020-12-14 06:16
      var iweil = sil.Select(item=> new InvoiceWithEntryInfo {
                     IdIWEI = item.ID,
                     AmountIWEI = item.Amount,
                     DateIWEI = item.Date}).ToList();
    
    0 讨论(0)
  • 2020-12-14 06:16

    Just use Select:

    if(sil != null)
    {
       var iweil = sil.Select(item=>new InvoiceWithEntryInfo()
                {
                    IdIWEI = item.ID,
                    AmountIWEI = item.Amount,
                    DateIWEI = item.Date
                }).ToList();
    }
    
    0 讨论(0)
  • 2020-12-14 06:25

    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).

    0 讨论(0)
  • 2020-12-14 06:27

    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.

    0 讨论(0)
  • 2020-12-14 06:30
    var iweilCopy = sil.Select(item => new InvoiceWithEntryInfo()
    {
      IdWEI = item.Id,
      NameWEI = item.Name,
      ....
    }).ToList();
    
    0 讨论(0)
提交回复
热议问题