LINQ Select语句中的条件数学

时间:2015-10-20 16:57:19

标签: c# .net linq

我有以下选择:

q.Select(c => new SomeObject
    {
        Invoices = c.SomeList.Sum(sl => sl.SomeValue),
        Payments = c.OtherList.Sum(ol => ol.OtherValue),
        Balance = ??? // Should be Payments - Invoices
    });

我想计算并将余额与对象的其余部分一起返回,但无法弄清楚如何在select语句中执行此操作。谢谢!

4 个答案:

答案 0 :(得分:6)

不需要匿名类型也不需要多次迭代。只需将Select表达式转换为代码块,然后使用局部变量。

    q.Select(c =>
                {
                    var invoices = c.SomeList.Sum(sl => sl.SomeValue);
                    var payments = c.OtherList.Sum(ol => ol.OtherValue);
                    // do stuff
                    return new SomeObject
                    {
                        Invoices = invoices,
                        Payments = payments,
                        Balance = payments - invoices
                    };
                });

正如@juharr建议的那样,您也可以将Balance设为只返回Payments - Invoices的只读属性。如果不需要设置Balance,这是建议的方法。

答案 1 :(得分:3)

您可以引入匿名类型来保存中间计算,然后从此类型创建SomeObject

q.Select(c => new 
              { Invoices = c.SomeList.Sum(sl => sl.SomeValue),
                Payments = c.OtherList.Sum(ol => ol.OtherValue)
              }
).Select(x => new SomeObject
              { Invoices = x.Invoices,
                Payments = x.Payments,
                Balance  = x.Payments - x.Invoices
              });

答案 2 :(得分:0)

您还可以使用let子句:

var query= from e in q
           let invoices= e.SomeList.Sum(sl => sl.SomeValue);
           let payments = e.OtherList.Sum(ol => ol.OtherValue);
           select new SomeObject
                      {
                        Invoices = invoices,
                        Payments = payments,
                        Balance = payments - invoices
                      };

答案 3 :(得分:-1)

无法在您需要第二个选择

的选择内部完成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<SomeObject> q = new List<SomeObject>();

            q.Select(c => new 
            {
                Invoices = c.SomeList.Sum(),
                Payments = c.OtherList.Sum(),

            }).Select(x => x.Payments - x.Invoices);

        }
    }
    public class SomeObject
    {
        public int[] SomeList { get; set; }
        public int[] OtherList { get; set; }
    }
}​