score:333
people.aggregate((curmin, x) => (curmin == null || (x.dateofbirth ?? datetime.maxvalue) <
curmin.dateofbirth ? x : curmin))
score:-1
you can use existing linq extension out there like morelinq. but if you just need only these methods, then you can use the simple code here:
public static ienumerable<t> minbys<t>(this ienumerable<t> collection, func<t, icomparable> selector)
{
var dict = collection.groupby(selector).todictionary(g => g.key);
return dict[dict.keys.min()];
}
public static ienumerable<t> maxbys<t>(this ienumerable<t> collection, func<t, icomparable> selector)
{
var dict = collection.groupby(selector).todictionary(g => g.key);
return dict[dict.keys.max()];
}
score:0
edit again:
sorry. besides missing the nullable i was looking at the wrong function,
min<(of <(tsource, tresult>)>)(ienumerable<(of <(tsource>)>), func<(of <(tsource, tresult>)>)) does return the result type as you said.
i would say one possible solution is to implement icomparable and use min<(of <(tsource>)>)(ienumerable<(of <(tsource>)>)), which really does return an element from the ienumerable. of course, that doesn't help you if you can't modify the element. i find ms's design a bit weird here.
of course, you can always do a for loop if you need to, or use the morelinq implementation jon skeet gave.
score:0
i was looking for something similar myself, preferably without using a library or sorting the entire list. my solution ended up similar to the question itself, just simplified a bit.
var min = people.min(p => p.dateofbirth);
var firstborn = people.firstordefault(p => p.dateofbirth == min);
score:0
another implementation, which could work with nullable selector keys, and for the collection of reference type returns null if no suitable elements found. this could be helpful then processing database results for example.
public static class ienumerableextensions
{
/// <summary>
/// returns the element with the maximum value of a selector function.
/// </summary>
/// <typeparam name="tsource">the type of the elements of source.</typeparam>
/// <typeparam name="tkey">the type of the key returned by keyselector.</typeparam>
/// <param name="source">an ienumerable collection values to determine the element with the maximum value of.</param>
/// <param name="keyselector">a function to extract the key for each element.</param>
/// <exception cref="system.argumentnullexception">source or keyselector is null.</exception>
/// <exception cref="system.invalidoperationexception">source contains no elements.</exception>
/// <returns>the element in source with the maximum value of a selector function.</returns>
public static tsource maxby<tsource, tkey>(this ienumerable<tsource> source, func<tsource, tkey> keyselector) => maxorminby(source, keyselector, 1);
/// <summary>
/// returns the element with the minimum value of a selector function.
/// </summary>
/// <typeparam name="tsource">the type of the elements of source.</typeparam>
/// <typeparam name="tkey">the type of the key returned by keyselector.</typeparam>
/// <param name="source">an ienumerable collection values to determine the element with the minimum value of.</param>
/// <param name="keyselector">a function to extract the key for each element.</param>
/// <exception cref="system.argumentnullexception">source or keyselector is null.</exception>
/// <exception cref="system.invalidoperationexception">source contains no elements.</exception>
/// <returns>the element in source with the minimum value of a selector function.</returns>
public static tsource minby<tsource, tkey>(this ienumerable<tsource> source, func<tsource, tkey> keyselector) => maxorminby(source, keyselector, -1);
private static tsource maxorminby<tsource, tkey>
(ienumerable<tsource> source, func<tsource, tkey> keyselector, int sign)
{
if (source == null) throw new argumentnullexception(nameof(source));
if (keyselector == null) throw new argumentnullexception(nameof(keyselector));
comparer<tkey> comparer = comparer<tkey>.default;
tkey value = default(tkey);
tsource result = default(tsource);
bool hasvalue = false;
foreach (tsource element in source)
{
tkey x = keyselector(element);
if (x != null)
{
if (!hasvalue)
{
value = x;
result = element;
hasvalue = true;
}
else if (sign * comparer.compare(x, value) > 0)
{
value = x;
result = element;
}
}
}
if ((result != null) && !hasvalue)
throw new invalidoperationexception("the source sequence is empty");
return result;
}
}
example:
public class a
{
public int? a;
public a(int? a) { this.a = a; }
}
var b = a.minby(x => x.a);
var c = a.maxby(x => x.a);
score:0
if you want to select object with minimum or maximum property value. another way is to use implementing icomparable.
public struct money : icomparable<money>
{
public money(decimal value) : this() { value = value; }
public decimal value { get; private set; }
public int compareto(money other) { return value.compareto(other.value); }
}
max implementation will be.
var amounts = new list<money> { new money(20), new money(10) };
money maxamount = amounts.max();
min implementation will be.
var amounts = new list<money> { new money(20), new money(10) };
money maxamount = amounts.min();
in this way, you can compare any object and get the max and min while returning the object type.
hope this will help someone.
score:0
a way via extension function on ienumerable that returns both the object and the minimum found. it takes a func that can do any operation on the object in the collection:
public static (double min, t obj) tmin<t>(this ienumerable<t> ienum,
func<t, double> afunc)
{
var oknull = default(t);
if (oknull != null)
throw new applicationexception("object passed to min not nullable");
(double amin, t okobj) best = (double.maxvalue, oknull);
foreach (t obj in ienum)
{
double q = afunc(obj);
if (q < best.amin)
best = (q, obj);
}
return (best);
}
example where object is an airport and we want to find closest airport to a given (latitude, longitude). airport has a dist(lat, lon) function.
(double okdist, airport best) greatestport = airports.tmin(x => x.dist(oklat, oklon));
score:1
try the following idea:
var firstborndate = people.groupby(p => p.dateofbirth).min(g => g.key).firstordefault();
score:1
you can just do it like order by and limit/fetch only trick in sql. so you order by dateofbirth ascending and then just fetch first row.
var query = from person in people
where person.dateofbirth!=null
orderby person.dateofbirth
select person;
var firstborn = query.take(1).tolist();
score:2
the following is the more generic solution. it essentially does the same thing (in o(n) order) but on any ienumerable types and can mixed with types whose property selectors could return null.
public static class linqextensions
{
public static t minby<t>(this ienumerable<t> source, func<t, icomparable> selector)
{
if (source == null)
{
throw new argumentnullexception(nameof(source));
}
if (selector == null)
{
throw new argumentnullexception(nameof(selector));
}
return source.aggregate((min, cur) =>
{
if (min == null)
{
return cur;
}
var mincomparer = selector(min);
if (mincomparer == null)
{
return cur;
}
var curcomparer = selector(cur);
if (curcomparer == null)
{
return min;
}
return mincomparer.compareto(curcomparer) > 0 ? cur : min;
});
}
}
tests:
var nullableints = new int?[] {5, null, 1, 4, 0, 3, null, 1};
assert.areequal(0, nullableints.minby(i => i));//should pass
score:3
public class foo {
public int bar;
public int stuff;
};
void main()
{
list<foo> foolist = new list<foo>(){
new foo(){bar=1,stuff=2},
new foo(){bar=3,stuff=4},
new foo(){bar=2,stuff=3}};
foo result = foolist.aggregate((u,v) => u.bar < v.bar ? u: v);
result.dump();
}
score:3
perfectly simple use of aggregate (equivalent to fold in other languages):
var firstborn = people.aggregate((min, x) => x.dateofbirth < min.dateofbirth ? x : min);
the only downside is that the property is accessed twice per sequence element, which might be expensive. that's hard to fix.
score:5
from .net 6 (preview 7) or later, there are new build-in method enumerable.maxby and enumerable.minby to achieve this.
var lastborn = people.maxby(p => p.dateofbirth);
var firstborn = people.minby(p => p.dateofbirth);
score:19
.net 6 supports maxby/minby natively. so you will be able to do this with a simple
people.minby(p => p.dateofbirth)
score:22
solution with no extra packages:
var min = lst.orderby(i => i.startdate).firstordefault();
var max = lst.orderby(i => i.startdate).lastordefault();
also you can wrap it into extension:
public static class linqextensions
{
public static t minby<t, tprop>(this ienumerable<t> source, func<t, tprop> propselector)
{
return source.orderby(propselector).firstordefault();
}
public static t maxby<t, tprop>(this ienumerable<t> source, func<t, tprop> propselector)
{
return source.orderby(propselector).lastordefault();
}
}
and in this case:
var min = lst.minby(i => i.startdate);
var max = lst.maxby(i => i.startdate);
by the way... o(n^2) is not the best solution. paul betts gave fatster solution than my. but my is still linq solution and it's more simple and more short than other solutions here.
score:59
so you are asking for argmin
or argmax
. c# doesn't have a built-in api for those.
i've been looking for a clean and efficient (o(n) in time) way to do this. and i think i found one:
the general form of this pattern is:
var min = data.select(x => (key(x), x)).min().item2;
^ ^ ^
the sorting key | take the associated original item
min by key(.)
specially, using the example in original question:
for c# 7.0 and above that supports value tuple:
var youngest = people.select(p => (p.dateofbirth, p)).min().item2;
for c# version before 7.0, anonymous type can be used instead:
var youngest = people.select(p => new {age = p.dateofbirth, ppl = p}).min().ppl;
they work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1
vs x2
, then y1
vs y2
. that's why the built-in .min
can be used on those types.
and since both anonymous type and value tuple are value types, they should be both very efficient.
note
in my above argmin
implementations i assumed dateofbirth
to take type datetime
for simplicity and clarity. the original question asks to exclude those entries with null dateofbirth
field:
null dateofbirth values are set to datetime.maxvalue in order to rule them out of the min consideration (assuming at least one has a specified dob).
it can be achieved with a pre-filtering
people.where(p => p.dateofbirth.hasvalue)
so it's immaterial to the question of implementing argmin
or argmax
.
note 2
the above approach has a caveat that when there are two instances that have the same min value, then the min()
implementation will try to compare the instances as a tie-breaker. however, if the class of the instances does not implement icomparable
, then a runtime error will be thrown:
at least one object must implement icomparable
luckily, this can still be fixed rather cleanly. the idea is to associate a distanct "id" with each entry that serves as the unambiguous tie-breaker. we can use an incremental id for each entry. still using the people age as example:
var youngest = enumerable.range(0, int.maxvalue)
.zip(people, (idx, ppl) => (ppl.dateofbirth, idx, ppl)).min().item3;
score:66
people.orderby(p => p.dateofbirth.getvalueordefault(datetime.maxvalue)).first()
would do the trick
score:165
note: i include this answer for completeness since the op didn't mention what the data source is and we shouldn't make any assumptions.
this query gives the correct answer, but could be slower since it might have to sort all the items in people
, depending on what data structure people
is:
var oldest = people.orderby(p => p.dateofbirth ?? datetime.maxvalue).first();
update: actually i shouldn't call this solution "naive", but the user does need to know what he is querying against. this solution's "slowness" depends on the underlying data. if this is a array or list<t>
, then linq to objects has no choice but to sort the entire collection first before selecting the first item. in this case it will be slower than the other solution suggested. however, if this is a linq to sql table and dateofbirth
is an indexed column, then sql server will use the index instead of sorting all the rows. other custom ienumerable<t>
implementations could also make use of indexes (see i4o: indexed linq, or the object database db4o) and make this solution faster than aggregate()
or maxby()
/minby()
which need to iterate the whole collection once. in fact, linq to objects could have (in theory) made special cases in orderby()
for sorted collections like sortedlist<t>
, but it doesn't, as far as i know.
score:249
unfortunately there isn't a built-in method to do this, but it's easy enough to implement for yourself. here are the guts of it:
public static tsource minby<tsource, tkey>(this ienumerable<tsource> source,
func<tsource, tkey> selector)
{
return source.minby(selector, null);
}
public static tsource minby<tsource, tkey>(this ienumerable<tsource> source,
func<tsource, tkey> selector, icomparer<tkey> comparer)
{
if (source == null) throw new argumentnullexception("source");
if (selector == null) throw new argumentnullexception("selector");
comparer ??= comparer<tkey>.default;
using (var sourceiterator = source.getenumerator())
{
if (!sourceiterator.movenext())
{
throw new invalidoperationexception("sequence contains no elements");
}
var min = sourceiterator.current;
var minkey = selector(min);
while (sourceiterator.movenext())
{
var candidate = sourceiterator.current;
var candidateprojected = selector(candidate);
if (comparer.compare(candidateprojected, minkey) < 0)
{
min = candidate;
minkey = candidateprojected;
}
}
return min;
}
}
example usage:
var firstborn = people.minby(p => p.dateofbirth ?? datetime.maxvalue);
note that this will throw an exception if the sequence is empty, and will return the first element with the minimal value if there's more than one.
alternatively, you can use the implementation we've got in morelinq, in minby.cs. (there's a corresponding maxby
, of course.)
install via package manager console:
pm> install-package morelinq
Source: stackoverflow.com
Related Query
- How to use LINQ to select object with minimum or maximum property value
- How to perform .Max() on a property of all objects in a collection and return the object with maximum value
- Get minimum and maximum time value from list of object property using Linq
- how to get the value member of a selected comboBox to use it to add a new object with linq
- How can I use LINQ to get the instance with the highest value of a property in a child list?
- How do you select an object with lowest property linq query syntax
- How to handle NULL object property with FirstOrDefault using Linq
- Using LINQ, how do I find an object with a given property value from a List?
- C# LINQ Select objects with the same value of one property join values of other
- How can I use linq to return integers in one array that do not match up with an integer property of another array?
- C# Create object with dynamic properties : LINQ select List<object> values by property names array
- How to use a LINQ query to include index in Select with F#
- How to use LINQ to select all descendants of a composite object
- How to use Linq to select and group complex child object from a parents list
- How can I use Distinct on a specific property and select the object to keep based on a predicate?
- How to filter a list with linq depends on counting a property at the same list and take a random group at least minimum total
- How to select objects with highest value of Property A, grouped by Property B?
- How to use OrderBy Linq when object is null and property is integer
- Get the objects with the maximum value for a specific property from a list using LINQ
- C# Collection select value of the property with minimum value of another property
- How to set a DTO's property value directly in LINQ select statement
- Complex Linq query to select list items with another list property containing a value
- select and update based on a child objects property minimum value using Linq
- How to use expression to assign property in LINQ Select new
- How to dynamically get a property value in which is in another property with Linq where statement
- How to select all objects sharing a property value with a property value in list of objects?
- Linq to entities use `Func` to create property in a select statement that produces an anonymous object
- How to merge two lists while adding metadata indicating value source with LINQ statement?
- How to use LINQ Select with Max() in C#
- How do i use linq and select just a Sum of values(field) from a datatable along with a where clause?
More Query from same tag
- LINQ (to objects) , running several queries over the same IEnumerable?
- Dynamics CRM Linq validation
- loop through IEnumerable and group by date and time span differences
- Need help transforming one kind of list into another kind of list using LINQ
- C# Linq question
- Linq - Order by StartsWith then Contains
- Linq on nested lists c#
- c# Linq select distinct date time days
- Error: The cast to value type 'System.Int32' failed because the materialized value is null
- Where condition inside lambda expression c#
- LINQ to SQL, Visual Basic - Listbox Receives the Query NOT the Result
- How to best handle a search query that includes 0 to 3 parameters/filters but using a single LinQ to Entities expression
- Dynamic Linq to Datatable Nullable Fields
- How to speed up Linq based data fetching & Looping into different tables?
- EF Distinct on IQueryable doesn't remove duplicates
- How to avoid repeating ToLists when using LINQ and Entity Framework?
- Get result from multiple where conditional statements in LINQ
- MVC linq keeps returning the last row of data
- c# xml linq correct way?
- how to combine multiple LINQ Expressions
- Search DataRow with Linq and delete from Dataset
- Directory with datetime+string key, and automatic removal of old entries
- Empty class to use with LINQtoCSV - vb.net
- Find Element when XPath is variable
- Read attributes values with linq
- Better way to remove characters that aren't ASCII 32 to 175 C#
- LINQ execution time
- how to return the query result as a specific object type in LINQ
- Is is possible to add .Where() on a child collection property using nhibernate linq?
- LINQ join error in Release mode