Perform calculation inside select statement in LINQ

前端 未结 5 914
攒了一身酷
攒了一身酷 2021-01-21 02:17

I have a situation where i have to calculate percentage of two values for example

IEnumerable result = 
    from r in renewalLists
    gro         


        
5条回答
  •  难免孤独
    2021-01-21 02:43

    Well, assuming that you want the ratio between 2 properties of the actual RenewalModel, why not declare a read-only property that either does the computation each time or on first use?

    class RenewalModel
    {
        public int desiredCalucation => 
           (PotentialRenewalCount/PotentialRenewalCount)*100;
    
        // ...
    }
    

    By the way, you probably want to use double and fix the formula to use proper variables and do its computations using floating points.

    You should also fix the typo in your variable name. Calucation is improperly spelled! Even worst, that name does tell much about the purpose of the property.

    A benefit of doing such property is that it allows for code reuse if multiple queries return that information, it prevent the value to be changed from the outside and it won't affect LINQ code generation.

    But since original code is not working and we do not have any example of what it should do, it is hard to guess what it should do.

提交回复
热议问题