从属于对象的所有列表中获取元素总数

ges*_*alt 2 c# linq

我得到了一些代码,其中包含由不同类型的列表组成的对象.我的意思的一个简单例子:

public class Account
{
    private long accountID;
    private List<string> accountHolders;
    private List<string> phoneNumbers;
    private List<string> addresses;

    public Account()
    {
        this.accountHolders = new List<string>();
        this.phoneNumbers = new List<string>();
        this.addresses = new List<string>();
    }

    public long AccountID
    {
        get
        {
            return this.accountID;
        }
        set
        {
            this.accountID = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于需求,我需要获取每个列表中的元素总数以进行验证.我有以下方法可行:

public class AccountParser
{
    // Some code
    public int CountElements(Account acct)
    {
        int count = 0;
        count += acct.accountHolders.Count();
        count += acct.phoneNumbers.Count();
        count += acct.addresses.Count();

        return count;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是想知道是否有更好的方法来做到这一点.我知道我可以使用Linq枚举List,但在这种情况下我似乎无法使其工作.

Mar*_*olo 5

你正在做的是正确的事情

您可以在一行中执行此操作而不声明任何变量

public int CountElements(Account acct)
{
    return acct.accountHolders.Count() + acct.phoneNumbers.Count() + acct.addresses.Count();
}
Run Code Online (Sandbox Code Playgroud)

但它没有太大变化.


列表的数量是静态的,因为该类是静态的,因此如果结构不会改变则使用Reflection是没有意义的.

现在,您可以拥有多个Account具有不同类型列表的类.在这种情况下,我将创建一个抽象AbsAccount类,它具有抽象的CountElements属性:

public abstract class AbsAccount 
{
    public abstract int CountElements { get; }
}

public class Account: AbsAccount 
{
    private List<string> accountHolders;
    private List<string> phoneNumbers;
    private List<string> addresses;

    public override int CountElements
    {
        get 
        {
            return this.accountHolders.Count() 
                + this.phoneNumbers.Count() 
                + this.addresses.Count(); 
        }
    }
}


public class AccountParser
{
    // Some code
    public int CountElements(AbsAccount acct)
    {
        return acct.CountElements;
    }
}
Run Code Online (Sandbox Code Playgroud)

但也许我太过分了......