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 with ?:or maybe something else?

+3
source share
5 answers
public double GetAvgResult()
{
    // Assumes GetWeeklyValues() never returns null.
    return GetWeeklyValues().DefaultIfEmpty().Average();
}

Notice that this returns double, which I assume is what you really want (the average number of integers is logically not an integer). You can give it intif necessary or if you want to stick to integer math completely:

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

or

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

No matter how hard I try to do it. Is there any specific reason (other than the golf code) that you are trying to make with a low character count?

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

Source: https://habr.com/ru/post/1784790/


All Articles