score:1
Let's say your input data looks like this:
IEnumerable<Tuple<string, int>> firstSequence = ..., secondSequence = ...;
If the strings are unique in each sequence (i.e there can be no more than a single {"A", XXX} in either sequence) you can join
like this:
var query = from tuple1 in firstSequence
join tuple2 in secondSequence on tuple1.Item1 equals tuple2.Item1
select Tuple.Create(tuple1.Item1, tuple1.Item2 + tuple2.Item2);
You might also want to consider using a group by
, which would be more appropriate if this uniqueness doesn't hold:
var query = from tuple in firstSequence.Concat(secondSequence)
group tuple.Item2 by tuple.Item1 into g
select Tuple.Create(g.Key, g.Sum());
If neither is what you want, please clarify your requirements more precisely.
EDIT: After your clarification that these are dictionaries - your existing solution is perfectly fine. Here's another alternative with join
:
var joined = from kvp1 in dict1
join kvp2 in dict2 on kvp1.Key equals kvp2.Key
select new { kvp1.Key, Value = kvp1.Value + kvp2.Value };
var result = joined.ToDictionary(t => t.Key, t => t.Value);
or in fluent syntax:
var result = dict1.Join(dict2,
kvp => kvp.Key,
kvp => kvp.Key,
(kvp1, kvp2) => new { kvp1.Key, Value = kvp1.Value + kvp2.Value })
.ToDictionary(a => a.Key, a => a.Value);
score:0
If your intersection algorithm will result in anonymous type, i.e. ...Select(new { Key = key, Value = value})
then you can easily sum it
result.Sum(e => e.Value);
If you want to sum the "while" doing the intersection, add the value to the accumulator value when adding to the result set.
score:1
This will give the result, but there are some caveats. It does an union of the two collections and then it groups them by letter. So if, for example, col1
contained two A
elements, it would sum them together and, because now they are 2 A
, it would return them.
var col1 = new[] { new { L = "A", N = 5 }, new { L = "B", N = 3 }, new { L = "C", N = 2 } };
var col2 = new[] { new { L = "B", N = 1 }, new { L = "C", N = 8 }, new { L = "D", N = 6 } };
var res = col1.Concat(col2)
.GroupBy(p => p.L)
.Where(p => p.Count() > 1)
.Select(p => new { L = p.Key, N = p.Sum(q => q.N) })
.ToArray();
score:1
The best I came up with until now is (my collections are actually Dictionary<string, int>
instances):
var intersectingKeys = col1.Keys.Intersect(col2.Keys);
var intersection = intersectingKeys
.ToDictionary(key => key, key => col1[key] + col2[key]);
I'm not sure if it will perform well, at least is it readable.
Source: stackoverflow.com
Related Query
- Intersect and Sum lists with Linq
- Linq intersect with sum
- Linq query with nullable sum
- LINQ Lambda Group By with Sum
- Linq Sum with group by
- Intersect with a custom IEqualityComparer using Linq
- Linq Query with SUM and ORDER BY
- Sum nested values with Linq
- LINQ Query with GROUP and SUM
- LINQ sum collection of items to return object with results (multiple columns)
- Sum method in LINQ with long type
- Problem with LINQ to Entities query using Sum on child object property
- Sum a collection of objects which contain numeric properties only with LINQ
- LINQ with Lambda expression - Join, Group By, Sum and Count
- Linq to Sql with lambda sum as a where condition
- LINQ Sum with GroupBy
- LINQ Source Code Available
- LINQ Sum Nested collection with GroupBy and OrderByDescending
- Linq with where clause in many-to-many EF Code First object
- Linq Intersect with arrays
- LINQ won't sum a group with a float? property
- LINQ Query with both CASE statement and SUM function
- Intersect method in LINQ with C#
- C# - Linq optimize code with List and Where clause
- Using LINQ on ObservableCollection with GroupBy and Sum aggregate
- creating Linq to sqlite dbml from DbLinq source code
- Stubbing Code for Test With Linq Expressions and Lambdas
- Reuse Linq to SQL code with entityframework
- C# - Code supposed to be unreachable when calculate value in LINQ sum method
- Replacing loops with linq code
More Query from same tag
- Many-To-Many Entity Framework Update
- Case sensitive varchar match with LINQ
- linq query to get all child elements by passing parent id
- Using Linq building a Search query dealing with String.Empty
- Looping though an array, taking a subset at each iteration and store into list of objects
- Linq`s Intersect does not call GetHashCode
- Reset identity Column to 0
- System.NotSupportedException This overload of the method 'System.Linq.Queryable.GroupBy' is currently not supported.'
- Search IList of KeyValuePairs for two keys
- C# List of different object types: Better way than Zip to check equality
- Object Oriented Model on top of LINQ to SQL
- How to convert Null to String with Linq to Entity
- Searching listview items using Linq
- Linq to entities with EF in an specific relational model
- Sort and Match List Item
- How do I navigate through multiple relationships using LINQ to Entities?
- LINQtoCSV (or Other Libs): How To Export (to CSV file) Dynamic Number of Fields in a Class
- Querying Datatable with where condition
- indexof array using linq except
- Is LINQ's Any method efficient?
- Getting Stackoverflow exception when executing LINQ IQueryable method
- How to optimize method with nested if condition
- Convert sql select to LINQ
- Adding or to linq query
- Sort a list from another list IDs
- Issue with Simultaneous users making changes in a databound DataGridView
- Converting IFs to LINQ
- Does IEnumerable<TSource> Concat<TSource> preserve the order of elements?
- LINQ: ...Where(x => x.Contains(string that start with "foo"))
- "Cannot call methods on DateTime", and other limitations