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 Articles
- Intersect with a custom IEqualityComparer using Linq
- LINQ Source Code Available
- Linq with where clause in many-to-many EF Code First object
- Linq Intersect with arrays
- Intersect method in LINQ with C#
- C# - Linq optimize code with List and Where clause
- creating Linq to sqlite dbml from DbLinq source code
- Intersect and Sum lists with Linq
- Stubbing Code for Test With Linq Expressions and Lambdas
- Reuse Linq to SQL code with entityframework
- Replacing loops with linq code
- Linq sub query when using a repository pattern with EF code first
- Linq to sql as object data source - designer problem with partial classes
- LINQ deferred execution with a function's result as source (e.g. Console.ReadLine)
- Accessing SQL Server time in code with LINQ
- How to swap the data source associated with a Linq query?
- Using LINQ intersect function with a non-primitive type
- Linq intersect with sum
- Can't add a new record with an integer value into database by using linq from code C#
- SQL Linq intersect with multiple columns
- Avoiding repeating code with Linq query + optional params
- How to merge two lists while adding metadata indicating value source with LINQ statement?
- Compiling Error with LINQ Sorting Code Using List<T>
- source code for LINQ 101 samples
- Linq Intersect with partial match
- Linq Intersect Comma Delimited String with List Containing Strings using Iqueriable
- how to write a Linq query with a EF code first Many to Many relationship
- Intersect or union with a custom IEqualityComparer using Linq
- C# Linq Intersect Hashset<T> in memory with IEnumerable<T> from filestream
- Using Linq intersect with sub values?
- Is it possible to get the result from LINQ GROUP BY into the IEnumerable List
- LINQ Query on ConcurrentDictionary of 19710 items slow
- Linq correlated subquery to same table on multiple columns
- In operator using linq query
- Group by not working with two columns, but does with one
- LINQ: How to join two datatable with dynamic keys
- How to check if all items in an array of strings are key in a NameValueCollection?
- LINQ to XML query in c#
- c# Connecting to database using MySQL
- How does c# interpret my query?
- Python's list comprehension vs .NET LINQ
- Sum(ABS(col)) in LInq
- Compare elements from two xml documents based on element value in C#
- linq distinct field
- LINQ OrderBy help needed
- code first join between table not appeared
- Group records stored in one-dimensional array using LINQ
- How to use Linq group a order list by Date
- Create List<int> from a list<class>
- Compare lists and get values with Linq