How to allow average to be null [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how do i allow this get to be null?
public double? GetSignalAverage
{
get
{
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
SignalStrength is an Int

Check if the collection is null or empty:
public double? GetSignalAverage
{
get
{
if(Gsmdata == null || GsmData.Count() == 0)
return null;
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}

You'll have to declare SignalStrength as int? to allow null values. (If you don't, int will be its default value, which is 0.) But even then, Average() will simply ignore those values, if there is any non-null element (see the documentation).
If they all are null, Average will return null, which you can catch and return, like this:
double? signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
if(signalaverage == null)
{
return signalaverage; // which is essentially 'return null;'
}
else
{
return Math.Round(signalaverage, 2);
}

Related

How can I change the value returned in a C# get, set? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this code that gets the value of a setting:
public static BTN Btns {
get => (BTN)App.DB.GetSet(SET.Btns, 2, typeof(BTN));
set => App.DB.UpdSet(SET.Btns, (int)value);
}
How can I change this so that if the value returned from GetSet is 1, then the value returned from the get will be 1 and there will be a call to App.DB.UpdSet(SET.Btns, 2) issued to change it in the database to a 2?
Can I use {} or something like that after the => ?
Firstly, if your property value is going to change after every get, you should perhaps change it to a method call - keeps things more explicit.
Secondly, you can achieve what you want by replacing your expression bodied get with a regular get, like so:
public static BTN Btns
{
get
{
var value = (BTN)App.DB.GetSet(SET.Btns, 2, typeof(BTN));
if ((int)value == 1)
{
App.DB.UpdSet(SET.Btns, (int)value + 1);
}
return value;
}
set
{
App.DB.UpdSet(SET.Btns, (int)value);
}
}

Is there more efficient way to use !=? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Sometimes i need to use != two, three or four times is there a better way to do it?
if (result != 1 && result != 12)
{
do something
}
if (result != 1 && != 12)
{
do something
}
second option would be better, nut we all know it doesn't work
There is not a direct way in the language like the one you suggested:
// Wont compile
if (result != 1 && != 12) { }
If you only have a few values to check, I'd use the explicit comparsions. However you can create a collection of values an check if the result is not in the colleciton:
// using System.Linq;
if (!(new []{ 1, 2 /*, ... */ }).Contains(result)) { }
As suggested in the comments you can also write an extension method. This requires a public static class:
public static class ExtensionMethods
{
public static bool NotIn(this int num, params int[] numbers)
{
return !numbers.Contains(num);
}
}
// usage
result.NotIn(1, 12);
result.NotIn(1, 12, 3, 5, 6);
And if you want to compare not only integers, you can write a generic method:
public static bool NotIn<T>(this T element, params T[] collection)
{
return !collection.Contains(element);
}
// Works with different types
result.NotIn(1, 2, 3, 4);
"a".NotIn("b", "c", "aa");
You can use Linq All() method probably
if((new int[]{1,12,13}).All(x => x != result))
{
// do something
}

Optimize if -else statement Ask [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have below if-else statement, and I want to optimize it more.
Is there any way to optimize it more
if(entity[attributeName] != null)
{
if (entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
}
else
{
if (entity.FormattedValues.Contains(attributeName))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
}
If it's just for length of code, you could rewrite it like so:
if (entity.FormattedValues.Contains(attributeName)
&& (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference)))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
Or expressed as a ternary statement:
return entity.FormattedValues.Contains(attributeName)
&& (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference))
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
I've simplified your original code down to boolean values in an example here:
v1 (entity[attributeName] != null),
v2 (entity.FormattedValues.Contains(attributeName))
v3 (entity[attributeName].GetType() != typeof(EntityReference))
Note that you should generally write your code in a way that promotes legibility over brevity.
If I understand you mean correctly, your code can be rewritten like this:
if(entity[attributeName] != null)
{
return entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference)
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
}
return entity.FormattedValues.Contains(attributeName)
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
P/S: This way has nothing to do with: it made the code run faster or it saves memory while running or something like that. Just for readability.

Define if statement for property in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
public class hamid
{
private int[] arr = new int[10];
public int[] Arr
{
get => arr;
set
{
if (value < 0)
Environment.Exit(1);
else arr = value;
}
} // If in error.
}
I want have a if statement. For example if (values < 0)
But I have an error, please help me.
value is an array of integer, it can't be zero. Any element in the array could be zero. If you are trying to determine if the array is null, then you could change the check to be:
if (value == null)
{
Environment.Exit(1);
}

Why does Dictionary.ContainsKey throw ArgumentNullException? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The documentation states that bool Dictionary<TKey, TValue>.ContainsKey(TKey key) throws an exception in case a null key is passed. Could anyone give a reason for that? Wouldn't it be more practical if it just returned false?
If ContainsKey(null) returned false it would give the misleading impression that null keys are allowed..
This is how it is implemented: (Source)
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
And the method FindEntry as:
private int FindEntry(TKey key) {
if( key == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null) {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
Since having a null value as key in dictionary is not allowed.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add(null, 10);
The above would produce an exception:
Value cannot be null. Parameter name: key
For your question:
Wouldn't it be more practical if it just returned false?
Someone from Microsoft could probably reply that. But IMO, since adding a null value for key is not allowed there is no point in checking for null key in ContainsKey

Categories

Resources