user441365
user441365

Reputation: 4024

refactor LINQ function

How could I refactor this function so it could take any many to many parameters?

Program has many to many parameters as in Age, Color, etc...

So I have this function:

public int GetAgesOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Ages.Any()
        select x.Ages).Count();
}

but I also need this one:

public int GetColorsOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Colors.Any()
        select x.Colors).Count();
}

As I have up to 10 many to many relationships in Program, I guess it makes sense to have a single function that handles that?

EDIT: How could I return the Age or Color List, rather than an int as in:

public IEnumerable<Color> GetColorsOnProgram(IEnumerable<Program> ProgramList)
{
    return (from x in ProgramList
        where x.Colors.Any()
        select x.Colors);
}

Upvotes: 3

Views: 152

Answers (3)

Jamiec
Jamiec

Reputation: 136084

In addition to @Wouter's correct answer, and in answer to your edit, you could add a method like:

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

And then use it like:

GetItemsOnProgram(programList, x => x.Ages);

To get a list of all the ages in all the programs. This will not be a distinct list, but you can alsways tag a Distinct() on the end - albeit you may need to provide a Comparer to tell it how to make items distinct. See here for documentation.

Upvotes: 0

Rawling
Rawling

Reputation: 50104

Just call programList.Count(p => p.Ages.Any()), programList.Count(p => p.Colors.Any()) etc.

For your edit, if you want a single list of all the colors (or whatever) in any of your programs, you want programList.SelectMany(p => p.Colors), possibly followed by .Distinct().

Upvotes: 3

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can change your function to:

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

And then call it with:

GetCountOnProgram(programList, x => x.Ages.Any());

Upvotes: 1

Related Questions