C# 重构LINQ函数

C# 重构LINQ函数,c#,linq,C#,Linq,我如何重构这个函数,使它可以接受任意多对多的参数 程序有很多参数,如年龄、颜色等 所以我有这个函数: public int GetAgesOnProgram(IEnumerable<Program> ProgramList) { return (from x in ProgramList where x.Ages.Any() select x.Ages).Count(); } public int GetAgesOnProgram(IEnum

我如何重构这个函数,使它可以接受任意多对多的参数

程序有很多参数,如年龄、颜色等

所以我有这个函数:

public int GetAgesOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Ages.Any()
        select x.Ages).Count();
}
public int GetAgesOnProgram(IEnumerable programmalist)
{
返回(从程序列表中的x开始)
其中x.age.Any()
选择x.age).Count();
}
但我也需要这个:

public int GetColorsOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Colors.Any()
        select x.Colors).Count();
}
public int GetColorsOnProgram(IEnumerable ProgramList)
{
返回(从程序列表中的x开始)
其中x.Colors.Any()
选择x.Colors).Count();
}
由于我在程序中有多达10个多对多关系,我想用一个函数来处理它是有意义的

编辑: 我如何才能返回年龄或颜色列表,而不是像中那样返回整数:

public IEnumerable<Color> GetColorsOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Colors.Any()
        select x.Colors);
}
public IEnumerable GetColorsOn程序(IEnumerable程序列表)
{
返回(从程序列表中的x开始)
其中x.Colors.Any()
选择x(颜色);
}

您可以将功能更改为:

public int GetCountOnProgram(IEnumerable<Program> ProgramList, Func<Program,bool> whereClause)
{
    return ProgramList.Where(whereClause).Count();
}

只需调用
programList.Count(p=>p.Ages.Any())
programList.Count(p=>p.Colors.Any())


对于您的编辑,如果您想要任何程序中所有颜色(或任何颜色)的单一列表,您需要
programList。选择Many(p=>p.colors)
,除了@Wouter的正确答案之外,还可能后跟
.Distinct()
,在回答您的编辑时,您可以添加如下方法:

public static IEnumerable<T> GetItemsOnProgram<T>(IEnumerable<ProgramItem> ProgramList, Func<ProgramItem,IEnumerable<T>> selectClause)
{
    return ProgramList.SelectMany(selectClause);
}

获取所有程序中所有年龄的列表。这将不是一个不同的列表,但您也可以在末尾标记一个
distinct()
——尽管您可能需要提供一个
比较器来告诉它如何使项目不同。有关文档,请参阅。

该方法是否应该重命名为
GetCountOnProgram(..)
,因为它已不再是一个过时的方法了?另外,谢谢-直到现在我才意识到
Count
有一个重载,它使用了谓词。
public static IEnumerable<T> GetItemsOnProgram<T>(IEnumerable<ProgramItem> ProgramList, Func<ProgramItem,IEnumerable<T>> selectClause)
{
    return ProgramList.SelectMany(selectClause);
}
GetItemsOnProgram(programList, x => x.Ages);