I'm producing a list of decimal values from a LINQ expression and I want the minimum non zero value. However it's entirely possible that the LINQ expression will result in an empty list.
This will raise an exception and there is no MinOrDefault to cope with this situation.
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).Min();
How can I set the result to 0 if the list is empty?
What you want is this:
IEnumerable<double> results = ... your query ...
double result = results.MinOrDefault();
Well, MinOrDefault() does not exist. But if we were to implement it ourselves it would look something like this:
public static class EnumerableExtensions
{
public static T MinOrDefault<T>(this IEnumerable<T> sequence)
{
if (sequence.Any())
{
return sequence.Min();
}
else
{
return default(T);
}
}
}
However, there is functionality in System.Linq that will produce the same result (in a slightly different way):
double result = results.DefaultIfEmpty().Min();
If the results sequence contains no elements, DefaultIfEmpty() will produce a sequence containing one element - the default(T) - which you subsequently can call Min() on.
If the default(T) is not what you want, then you could specify your own default with:
double myDefault = ...
double result = results.DefaultIfEmpty(myDefault).Min();
Now, that's neat!
decimal? result = (from Item itm in itemList
where itm.Amount != 0
select (decimal?)itm.Amount).Min();
Note the conversion to decimal?. You'll get an empty result if there are none (just handle that after the fact - I'm mainly illustrating how to stop the exception). I also made "non-zero" use != rather than >.
The neatest in terms of just doing it once in a small amount code is, as already mentioned:
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).DefaultIfEmpty().Min();
With casting itm.Amount to decimal? and obtaining the Min of that being the neatest if we want to be able to detect this empty condition.
If however you want to actually provide a MinOrDefault() then we can of course start with:
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).Min();
}
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source)
{
return source.DefaultIfEmpty(defaultValue).Min();
}
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).Min(selector);
}
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
{
return source.DefaultIfEmpty().Min(selector);
}
You now have a full set of MinOrDefault whether or not you include a selector, and whether or not you specify the default.
From this point on your code is simply:
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).MinOrDefault();
So, while it's not as neat to begin with, it's neater from then on.
But wait! There's more!
Let's say you use EF and want to make use of the async support. Easily done:
public static Task<TSource> MinOrDefaultAsync<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).MinAsync();
}
public static Task<TSource> MinOrDefaultAsync<TSource>(this IQueryable<TSource> source)
{
return source.DefaultIfEmpty(defaultValue).MinAsync();
}
public static Task<TSource> MinOrDefaultAsync<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).MinAsync(selector);
}
public static Task<TSource> MinOrDefaultAsync<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
{
return source.DefaultIfEmpty().MinAsync(selector);
}
(Note that I don't use await here; we can directly create a Task<TSource> that does what we need without it, and hence avoid the hidden complications await brings).
But wait, there's more! Let's say we're using this with IEnumerable<T> some times. Our approach is sub-optimal. Surely we can do better!
First, the Min defined on int?, long?, float? double? and decimal? already do what we want anyway (as Marc Gravell's answer makes use of). Similarly, we also get the behaviour we want from the Min already defined if called for any other T?. So let's do some small, and hence easily inlined, methods to take advantage of this fact:
public static TSource? MinOrDefault<TSource>(this IEnumerable<TSource?> source, TSource? defaultValue) where TSource : struct
{
return source.Min() ?? defaultValue;
}
public static TSource? MinOrDefault<TSource>(this IEnumerable<TSource?> source) where TSource : struct
{
return source.Min();
}
public static TResult? Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult?> selector, TResult? defaultValue) where TResult : struct
{
return source.Min(selector) ?? defaultValue;
}
public static TResult? Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult?> selector) where TResult : struct
{
return source.Min(selector);
}
Now let's start with the more general case first:
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
if(default(TSource) == null) //Nullable type. Min already copes with empty sequences
{
//Note that the jitter generally removes this code completely when `TSource` is not nullable.
var result = source.Min();
return result == null ? defaultValue : result;
}
else
{
//Note that the jitter generally removes this code completely when `TSource` is nullable.
var comparer = Comparer<TSource>.Default;
using(var en = source.GetEnumerator())
if(en.MoveNext())
{
var currentMin = en.Current;
while(en.MoveNext())
{
var current = en.Current;
if(comparer.Compare(current, currentMin) < 0)
currentMin = current;
}
return currentMin;
}
}
return defaultValue;
}
Now the obvious overrides that make use of this:
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source)
{
var defaultValue = default(TSource);
return defaultValue == null ? source.Min() : source.MinOrDefault(defaultValue);
}
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
{
return source.Select(selector).MinOrDefault(defaultValue);
}
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
return source.Select(selector).MinOrDefault();
}
If we're really bullish about performance, we can optimise for certain cases, just like Enumerable.Min() does:
public static int MinOrDefault(this IEnumerable<int> source, int defaultValue)
{
using(var en = source.GetEnumerator())
if(en.MoveNext())
{
var currentMin = en.Current;
while(en.MoveNext())
{
var current = en.Current;
if(current < currentMin)
currentMin = current;
}
return currentMin;
}
return defaultValue;
}
public static int MinOrDefault(this IEnumerable<int> source)
{
return source.MinOrDefault(0);
}
public static int MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector, int defaultValue)
{
return source.Select(selector).MinOrDefault(defaultValue);
}
public static int MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
{
return source.Select(selector).MinOrDefault();
}
And so on for long, float, double and decimal to match the set of Min() provided by Enumerable. This is the sort of thing where T4 templates are useful.
At the end of all that, we have just about as performant an implementation of MinOrDefault() as we could hope for, for a wide range of types. Certainly not "neat" in the face of one use for it (again, just use DefaultIfEmpty().Min()), but very much "neat" if we find ourselves using it a lot, so we have a nice library we can reuse (or indeed, paste into answers on StackOverflow…).
This approach will return the single smallest Amount value from itemList. In theory this should avoid multiple round trips to the database.
decimal? result = (from Item itm in itemList
where itm.Amount > 0)
.Min(itm => (decimal?)itm.Amount);
The null reference exception is no longer caused because we are using a nullable type.
By avoiding the use of executing methods such as Any before calling Min, we should only be making one trip to the database
If itemList is non-nullable (where DefaultIfEmpty gives 0) and you want null as a potential output value, you can use the lambda syntax as well:
decimal? result = itemList.Where(x => x.Amount != 0).Min(x => (decimal?)x);
decimal result;
try{
result = (from Item itm in itemList
where itm.Amount != 0
select (decimal?)itm.Amount).Min();
}catch(Exception e){
result = 0;
}
Related
One of IEnumerable's overload is:
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);
In the selector I wish to include the source. I know this sounds counter-intuitive because you provide the source to Select in the first place, but JavaScript has something similar. I would want to use it in a quick situation like this one here:
var greetings = new List<string> { "John", "Keith", "Sarah", "Matt" }.Select((name, index, source) => {
if (name == source.First())
return $"{name} (Todays Winner)";
return name;
});
The above will have an error because Select's selector parameter does not return 3 values. Just the current object, and index. I want it to include the source.
I don't want to first create the list separately and then do .first on it.
Here is how far I've gone with the extension; I'm not sure how to implement it.
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult, IEnumerable<TSource>> selector)
{
//not sure what to put in here, must be missing something simple ;(
}
Update
The above situation is just a made up example. My actual case requires using .Last() not .First() so index won't be useful since we don't know what the last index will be, as opposed to zero being first. Hence my need for the source to be passed back.
This should do it:
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TSource>, TResult> selector)
{
using (var enumerator = source.GetEnumerator()) {
for (var i = 0 ; enumerator.MoveNext() ; i++) {
yield return selector(enumerator.Current, i, source);
}
}
}
Note that you have written the wrong type for the selector parameter. It should be Func<TSource, int, IEnumerable<TSource>, TResult>, not Func<TSource, int, TResult, IEnumerable<TSource>>.
If you just want to check if an element is the first, why not just check index == 0?
var greetings = new List<string> { "John", "Keith", "Sarah", "Matt" }.Select((name, index, source) => {
if (index == 0)
return $"{name} (Todays Winner)";
return name;
});
This should work:
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TSource>, TResult> selector)
{
int index = 0;
foreach(var item in source)
{
yield return selector(item, index, source);
index++;
}
}
I'm producing a list of decimal values from a LINQ expression and I want the minimum non zero value. However it's entirely possible that the LINQ expression will result in an empty list.
This will raise an exception and there is no MinOrDefault to cope with this situation.
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).Min();
How can I set the result to 0 if the list is empty?
What you want is this:
IEnumerable<double> results = ... your query ...
double result = results.MinOrDefault();
Well, MinOrDefault() does not exist. But if we were to implement it ourselves it would look something like this:
public static class EnumerableExtensions
{
public static T MinOrDefault<T>(this IEnumerable<T> sequence)
{
if (sequence.Any())
{
return sequence.Min();
}
else
{
return default(T);
}
}
}
However, there is functionality in System.Linq that will produce the same result (in a slightly different way):
double result = results.DefaultIfEmpty().Min();
If the results sequence contains no elements, DefaultIfEmpty() will produce a sequence containing one element - the default(T) - which you subsequently can call Min() on.
If the default(T) is not what you want, then you could specify your own default with:
double myDefault = ...
double result = results.DefaultIfEmpty(myDefault).Min();
Now, that's neat!
decimal? result = (from Item itm in itemList
where itm.Amount != 0
select (decimal?)itm.Amount).Min();
Note the conversion to decimal?. You'll get an empty result if there are none (just handle that after the fact - I'm mainly illustrating how to stop the exception). I also made "non-zero" use != rather than >.
The neatest in terms of just doing it once in a small amount code is, as already mentioned:
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).DefaultIfEmpty().Min();
With casting itm.Amount to decimal? and obtaining the Min of that being the neatest if we want to be able to detect this empty condition.
If however you want to actually provide a MinOrDefault() then we can of course start with:
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).Min();
}
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source)
{
return source.DefaultIfEmpty(defaultValue).Min();
}
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).Min(selector);
}
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
{
return source.DefaultIfEmpty().Min(selector);
}
You now have a full set of MinOrDefault whether or not you include a selector, and whether or not you specify the default.
From this point on your code is simply:
decimal result = (from Item itm in itemList
where itm.Amount > 0
select itm.Amount).MinOrDefault();
So, while it's not as neat to begin with, it's neater from then on.
But wait! There's more!
Let's say you use EF and want to make use of the async support. Easily done:
public static Task<TSource> MinOrDefaultAsync<TSource>(this IQueryable<TSource> source, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).MinAsync();
}
public static Task<TSource> MinOrDefaultAsync<TSource>(this IQueryable<TSource> source)
{
return source.DefaultIfEmpty(defaultValue).MinAsync();
}
public static Task<TSource> MinOrDefaultAsync<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TSource defaultValue)
{
return source.DefaultIfEmpty(defaultValue).MinAsync(selector);
}
public static Task<TSource> MinOrDefaultAsync<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
{
return source.DefaultIfEmpty().MinAsync(selector);
}
(Note that I don't use await here; we can directly create a Task<TSource> that does what we need without it, and hence avoid the hidden complications await brings).
But wait, there's more! Let's say we're using this with IEnumerable<T> some times. Our approach is sub-optimal. Surely we can do better!
First, the Min defined on int?, long?, float? double? and decimal? already do what we want anyway (as Marc Gravell's answer makes use of). Similarly, we also get the behaviour we want from the Min already defined if called for any other T?. So let's do some small, and hence easily inlined, methods to take advantage of this fact:
public static TSource? MinOrDefault<TSource>(this IEnumerable<TSource?> source, TSource? defaultValue) where TSource : struct
{
return source.Min() ?? defaultValue;
}
public static TSource? MinOrDefault<TSource>(this IEnumerable<TSource?> source) where TSource : struct
{
return source.Min();
}
public static TResult? Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult?> selector, TResult? defaultValue) where TResult : struct
{
return source.Min(selector) ?? defaultValue;
}
public static TResult? Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult?> selector) where TResult : struct
{
return source.Min(selector);
}
Now let's start with the more general case first:
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
if(default(TSource) == null) //Nullable type. Min already copes with empty sequences
{
//Note that the jitter generally removes this code completely when `TSource` is not nullable.
var result = source.Min();
return result == null ? defaultValue : result;
}
else
{
//Note that the jitter generally removes this code completely when `TSource` is nullable.
var comparer = Comparer<TSource>.Default;
using(var en = source.GetEnumerator())
if(en.MoveNext())
{
var currentMin = en.Current;
while(en.MoveNext())
{
var current = en.Current;
if(comparer.Compare(current, currentMin) < 0)
currentMin = current;
}
return currentMin;
}
}
return defaultValue;
}
Now the obvious overrides that make use of this:
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source)
{
var defaultValue = default(TSource);
return defaultValue == null ? source.Min() : source.MinOrDefault(defaultValue);
}
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
{
return source.Select(selector).MinOrDefault(defaultValue);
}
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
return source.Select(selector).MinOrDefault();
}
If we're really bullish about performance, we can optimise for certain cases, just like Enumerable.Min() does:
public static int MinOrDefault(this IEnumerable<int> source, int defaultValue)
{
using(var en = source.GetEnumerator())
if(en.MoveNext())
{
var currentMin = en.Current;
while(en.MoveNext())
{
var current = en.Current;
if(current < currentMin)
currentMin = current;
}
return currentMin;
}
return defaultValue;
}
public static int MinOrDefault(this IEnumerable<int> source)
{
return source.MinOrDefault(0);
}
public static int MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector, int defaultValue)
{
return source.Select(selector).MinOrDefault(defaultValue);
}
public static int MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
{
return source.Select(selector).MinOrDefault();
}
And so on for long, float, double and decimal to match the set of Min() provided by Enumerable. This is the sort of thing where T4 templates are useful.
At the end of all that, we have just about as performant an implementation of MinOrDefault() as we could hope for, for a wide range of types. Certainly not "neat" in the face of one use for it (again, just use DefaultIfEmpty().Min()), but very much "neat" if we find ourselves using it a lot, so we have a nice library we can reuse (or indeed, paste into answers on StackOverflow…).
This approach will return the single smallest Amount value from itemList. In theory this should avoid multiple round trips to the database.
decimal? result = (from Item itm in itemList
where itm.Amount > 0)
.Min(itm => (decimal?)itm.Amount);
The null reference exception is no longer caused because we are using a nullable type.
By avoiding the use of executing methods such as Any before calling Min, we should only be making one trip to the database
If itemList is non-nullable (where DefaultIfEmpty gives 0) and you want null as a potential output value, you can use the lambda syntax as well:
decimal? result = itemList.Where(x => x.Amount != 0).Min(x => (decimal?)x);
decimal result;
try{
result = (from Item itm in itemList
where itm.Amount != 0
select (decimal?)itm.Amount).Min();
}catch(Exception e){
result = 0;
}
I have a generic linked list, currently made up of ints, and I want to sort them by ascending order by default, and then switch a boolean to sort them by descending values. How would I go about doing this?
Assuming your linked list implements IEnumerable<T> (which it probably should!), you can just use the LINQ functions OrderBy and OrderByDescending.
For ints, the default comparer is fine, so you would just write:
bool ascending = true;
var orderedEnumerable = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x);
Or, with a function and default args:
IOrderedEnumerable<int> GetOrderedNumbers(bool ascending = true)
{
return ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x);
}
MSDN for OrderBy: http://msdn.microsoft.com/en-us/library/vstudio/bb534966(v=vs.100).aspx
If you use the .NET's LinkedList<T> that, in its turn, implements IEnumerable<T> you can use some of these solutions:
This extension method returns a sorted copy of type LinkedList<T>
public static LinkedList<TSource> SortedAscending<TSource, TKey>(
this LinkedList<TSource> source,
Func<TSource, TKey> keySelector)
{
LinkedList<TSource> tempLinkedList = new LinkedList<TSource>();
IEnumerable<TSource> orderedEnumerable = source.OrderBy(keySelector).AsEnumerable();
orderedEnumerable.ForEach(value => tempLinkedList.AddLast(value));
return tempLinkedList;
}
This extension method sorts the source of type LinkedList<T>
public static void SelfSortAscending<TSource, TKey>(
this LinkedList<TSource> source,
Func<TSource, TKey> keySelector)
{
LinkedList<TSource> tempLinkedList = new LinkedList<TSource>(source);
source.Clear();
IEnumerable<TSource> orderedEnumerable = tempLinkedList.OrderBy(keySelector).AsEnumerable();
orderedEnumerable.ForEach(value => source.AddLast(value));
}
Extension methods for descending ordering you can find at:
LinkedListHelper (GitHub link)
By the way, .ForEach() you could implement like this:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
foreach (T element in source)
action(element);
}
I'm pulling all of the advanced features together for this one, but haven't worked with generics or lambda expressions very much:
Here's example usage of the method I want to create:
MyClass mc = null;
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc
// the code has not failed at this point and the value of x is 0 (int's default)
// had mc and all of the properties expressed in the lambda expression been initialized
// x would be equal to mc.This.That.TheOther's value
Here's as far as I've gotten, but I'm not sure what to do with this expression object.
[1
Is this the sort of thing you're after?
public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> expression)
{
if (obj == null)
return default(TResult);
try
{
return expression(obj);
}
catch(NullReferenceException)
{
return default(TResult);
}
}
What you are trying to do sounds like Maybe.
Project Description:
Maybe or IfNotNull using lambdas for deep expressions in C#
int? CityId= employee.Maybe(e=>e.Person.Address.City);
Update: There is more discussion about how best to accomplish this sort of thing at this question.
Here's what I was after:
public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> function, TResult defaultResult = default(TResult))
{
try
{
defaultResult = function(obj);
}
catch (NullReferenceException) { }
return defaultResult;
}
The IEnumerable extension method FirstOrDefault didn't exactly do as I wanted so I created FirstOrValue. Is this a good way to go about this or is there a better way?
public static T FirstOrValue<T>(this IEnumerable<T> source, Func<T, bool> predicate, T value)
{
T first = source.FirstOrDefault(predicate);
return Equals(first, default(T)) ? value : first;
}
Your code is probably incorrect; you probably haven't considered all of the cases.
Of course, we cannot know if any code is correct or incorrect until we have a spec. So start by writing a one-line spec:
"FirstOrValue<T> takes a sequence of T, a predicate, and a value of T, and returns either the first item in the sequence that matches the predicate if there is one, or, if there is not, the stated value."
Does your attempt actually implement that spec? Certainly not! Test it:
int x = FirstOrValue<int>( new[] { -2, 0, 1 }, y=>y*y==y, -1);
this returns -1. The correct answer according to the spec is 0. The first item that matches the predicate is zero, so it should be returned.
A correct implementation of the spec would look like:
public static T FirstOrValue<T>(this IEnumerable<T> sequence, Func<T, bool> predicate, T value)
{
if (sequence == null) throw new ArgumentNullException("sequence");
if (predicate == null) throw new ArgumentNullException("predicate");
foreach(T item in sequence)
if (predicate(item)) return item;
return value;
}
Always write a spec first, even if it's only a single sentence.
default(T) will return null by default for reference types.
I would do this
public static T FirstOrValue<T>(this IEnumerable<T> source, Func<T, bool> predicate, T value)
{
T first = source.FirstOrDefault(predicate);
return first ?? value;
}
Since this is an overload, it's worth mentioning the version with no predicate.
public static T FirstOrValue<T>(this IEnumerable<T> sequence, T value)
{
if (sequence == null) throw new ArgumentNullException("sequence");
foreach(T item in sequence)
return item;
return value;
}
Seems reasonable to me if you want to tweak the readability instead of using DefaultIfEmpty.
You could also create an override that uses a lambda if the creation of the default value is expensive, creating it only if necessary.
public static T FirstOrValue<T>(this IEnumerable<T> source, Func<T, bool> predicate, Func<T> getValue)
{
T first = source.FirstOrDefault(predicate);
return Equals(first, default(T)) ? getValue() : first;
}