Vishal
Vishal

Reputation: 12369

A shorter way to write the following function in C#?

I have this function -

public int GetAvgResult()
{
 var weeklyvalues=GetWeeklyValues();//gets list of weekly values.
 if (weeklyvalues.Count == 0)
                return 0;
            return (weeklyvalues.Sum() / weeklyvalues.Count);
}

Is there a shorter way to write this using ?: or maybe something else ?

Upvotes: 3

Views: 205

Answers (5)

Ani
Ani

Reputation: 113402

public double GetAvgResult()
{
    // Assumes GetWeeklyValues() never returns null.
    return GetWeeklyValues().DefaultIfEmpty().Average();
}

Do note that this returns a double , which I assume is what you really want (the average of a bunch of integers is logically not an integer). You can cast it to int if necessary, or if you want to stick with integer math all the way:

var seq = GetWeeklyValues().DefaultIfEmpty();
return seq.Sum() / seq.Count();

Upvotes: 11

CaffGeek
CaffGeek

Reputation: 22054

public int GetAvgResult()
{
    var weeklyvalues=GetWeeklyValues();//gets list of weekly values.
    return weeklyvalues.Count == 0
        ? 0 
        : (weeklyvalues.Sum() / weeklyvalues.Count);
}

Upvotes: 1

Gavin H
Gavin H

Reputation: 10482

public int GetAvgResult()
{
 var weeklyvalues = GetWeeklyValues();//gets list of weekly values.
 return (weeklyvalues.Count == 0) ? 0 : (weeklyvalues.Sum() / weeklyvalues.Count );
}

Upvotes: 1

Mark
Mark

Reputation: 11740

public int GetAvgResult()
{
    var weeklyvalues = GetWeeklyValues(); //gets list of weekly values.
    return weeklyvalues.Count == 0 ? 0 : weeklyvalues.Sum() / weeklyvalues.Count;
}

That's as short as I'd attempt to make it. Is there a specific reason (other than code golf) you're trying for a low character count?

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

public int GetAvgResult()
{
    var weeklyvalues = GetWeeklyValues();
    return (weeklyvalues.Count != 0) ? (weeklyvalues.Sum() / weeklyvalues.Count) : 0;
}

or:

public int GetAvgResult()
{
    return GetWeeklyValues().DefaultIfEmpty().Average();
}

Upvotes: 2

Related Questions