score:4
var result = dict[someint].minby(kvp => kvp.value.value1 + kvp.value.value2).key;
using the minby extension method from the awesome morelinq project.
score:0
here is the non linq way. it is not shorter than its linq counterparts but it is much more efficient because it does no sorting like most linq solutions which may turn out expensive if the collection is large.
the minby solution from dtb is a good one but it requires an external library. i do like linq a lot but sometimes you should remind yourself that a foreach loop with a few local variables is not archaic or an error.
customstruct min(dictionary<double, customstruct> input)
{
customstruct lret = default(customstruct);
double lastsum = double.maxvalue;
foreach (var kvp in input)
{
var other = kvp.value;
var newsum = other.value1 + other.value2;
if (newsum < lastsum)
{
lastsum = newsum;
lret = other;
}
}
return lret;
}
if you want to use the linq method without using an extern library you can create your own minby like this one:
public static class extensions
{
public static t minby<t>(this ienumerable<t> coll, func<t,double> criteria)
{
t lret = default(t);
double last = double.maxvalue;
foreach (var v in coll)
{
var newlast = criteria(v);
if (newlast < last)
{
last = newlast;
lret = v;
}
}
return lret;
}
}
it is not as efficient as the first one but it does the job and is more reusable and composable as the first one. your solution with aggregate is innovative but requires recalculation of the sum of the current best match for every item the current best match is compared to because you carry not enough state between the aggregate calls.
score:0
thanks for all the help guys, found out this way too:
dict[int].aggregate(
(seed, o) =>
{
var v = seed.value.totalcut + seed.value.totalfill;
var k = o.value.totalcut + o.value.totalfill;
return v < k ? seed : o;
}).key;
score:1
using just plain linq:
dictionary<int, dictionary<double, customstruct>> dict = ...;
int id = ...;
var minimum =
(from kvp in dict[id]
// group the keys (double) by their sums
group kvp.key by kvp.value.value1 + kvp.value.value2 into g
orderby g.key // sort group keys (sums) in ascending order
select g.first()) // select the first key (double) in the group
.first(); // return first key in the sorted collection of keys
whenever you want to get the minimum or maximum item using plain linq, you usually have to do it using ith a combination of groupby()
, orderby()
and first()
/last()
to get it.
score:1
a dictionary<tkey,tvalue>
is also a sequence of keyvaluepair<tkey,tvalue>
. you can select the keyvaluepair with the least sum of values and and get its key.
using pure linq to objects:
dict[someint].orderby(item => item.value.value1 + item.value.value2)
.firstordefault()
.select(item => item.key);
Source: stackoverflow.com
Related Query
- Query Nested Dictionary
- How do we use a LINQ query on a Dictionary with a nested object?
- Populating nested dictionary from database query c#
- Linq query - reading nested XML to dictionary
- Convert Linq Query Result to Dictionary
- Nested query in entity framework
- Nested "from" LINQ query expressed with extension methods
- Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'
- Elegant way to create a nested Dictionary in C#
- How do I create a nested group-by dictionary using LINQ?
- How to query a nested list using a lambda expression
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Linq Query Dictionary where value in List
- How do I get the sum of the Counts of nested Lists in a Dictionary without using foreach?
- C# LINQ - convert nested dictionary to a list
- Query an XML file containing nested elements using LINQPad?
- Calling fellow code nerds - Alternatives to Nested Loops?
- Dapper nested object query - not populating all properties
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- linq to entity framework: use dictionary in query
- Query a Julia dictionary for certain values
- Query a Dictionary of Dictionaries?
- The nested query is not supported. Operation1='UnionAll' Operation2='MultiStreamNest'
- Need a linq to objects query for a nested collection
- convert query result to dictionary in vb.net
- C# + EntityFramework: Convert multiple group by query to nested JSON
- Nested LINQ query to select 'previous' value in a list
- Use dictionary inside linq query
- LINQ Source Code Available
- Nested LINQ Query Question
More Query from same tag
- How does PredicateBuilder work
- Call function using Mongodb-CSharp Driver
- linq select distinct date from a DataTable
- Retrieve all child elements' values (Linq Query)
- Learn LinqToSql or stick with ADO.NET?
- What is this linq code doing? Summarize something?
- Get different results with the same query in T-SQL and LINQ (EF Core)
- LINQ to Entities does not recognize the method
- Linq query in C# is not working as expected
- Multiple left joins in LINQ
- Select Distinct from DataTable using Linq and C#
- Listing only the last version of a row in a composite key
- EF5 Select objects based on child collection content
- How can you pre-define a variable that will contain an anonymous type?
- At what point is a LINQ data source determined?
- Validation for unique properties method
- Select clause null
- Filter a DbSet by the content of an IList using LINQ
- How to dynamically add descending to orderby?
- VB.NET LINQ Query: Getting The Sum of All Values For A Specific Structure Member
- LINQKit: nesting an ExpandableQuery in LINQ to Entities
- Position of .Take() has no effect on generated SQL
- LINQ to Entities - Subquery is coming back in chunks?
- How to sum a custom object with LinQ?
- Convert string response from webclient into array/list
- Linq To Nhibernate - Separated queries
- LINQ to SQL "aggregating" property
- Linq query in custom class
- How do I retrieve the value of an attribute in a parent if one of the elements of a child equals to a value?
- Asp MVC Entity Framework Check if Permission Is In Role