[英]Is there a more elegant way to sum multiple properties?
我有一个包含多个Int32类型的属性的类:
public class MyClass
{
public int C1 { get; set; }
public int C2 { get; set; }
public int C3 { get; set; }
.
.
.
public int Cn { get; set; }
}
我想总结所有这些属性。 而不是做:
int sum = C1 + C2 + C3 + ... + Cn
有没有更有效/更优雅的方法?
您可以伪造它,但是我不确定它有多有用:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var test = new MyClass();
// ...
int sum = test.All().Sum();
}
}
public class MyClass
{
public int C1 { get; set; }
public int C2 { get; set; }
public int C3 { get; set; }
// ...
public int Cn { get; set; }
public IEnumerable<int> All()
{
yield return C1;
yield return C2;
yield return C3;
// ...
yield return Cn;
}
}
}
如果您确实要执行求和而不需要键入每个属性,则可以使用反射来遍历属性,但这会带来很大的性能成本。 但是,为了娱乐,您可以执行以下操作:
var item = new MyClass();
// Populate the values somehow
var result = item.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(Int32))
.Select(pi => Convert.ToInt32(pi.GetValue(item, null)))
.Sum();
PS:不要忘记using System.Reflection;
添加using System.Reflection;
指示。
也许您可以使用具有IEnumarable接口与自定义类的数组或数据结构。 然后,您可以使用linq执行Sum()。
如果非常需要将值存储在单独的成员(属性,字段)中,那么是的,这是唯一的方法。 但是,如果有数字列表,请将其存储在列表中,而不要存储在单独的成员中。
或者,丑陋的:
new[]{C1,C2,C3,C4}.Sum()
但是无论如何,字符比单个“ +”更多。
public class MyClass
{
readonly int[] _cs = new int[n];
public int[] Cs { get { return _cs; } }
public int C1 { get { return Cs[0]; } set { Cs[0] = value; } }
public int C2 { get { return Cs[1]; } set { Cs[1] = value; } }
public int C3 { get { return Cs[2]; } set { Cs[2] = value; } }
.
.
.
public int Cn { get { return Cs[n-1]; } set { Cs[n-1] = value; } }
}
现在,您可以将Enumerable.Sum
与MyClass.Cs
使用,并且仍可以将C1
, C2
,...映射到数据库字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.