Using Linq to combine two lists and get total quantity - c#

I have the following two lists coming from two different warehouses.
var list1 = new List<Tshirt> {
new Tshirt(){ Color = "blue", size="M", qty=3 },
new Tshirt(){ Color = "red", size="M", qty=2 },
new Tshirt(){ Color = "green", size="M", qty=3 },
new Tshirt(){ Color = "blue", size="M", qty=3 },
}
var list2 = new List<Tshirt> {
new Tshirt(){ Color = "blue", size="M", qty=5 },
new Tshirt(){ Color = "red", size="M", qty=7 },
}
Using LINQ, how do I end up with a combined list like this.
var list3 = new List<Tshirt> {
new Tshirt(){ Color = "blue", size="M", qty=11 },
new Tshirt(){ Color = "red", size="M", qty=9 },
new Tshirt(){ Color = "green", size="M", qty=3 }
}

(I originally answered this question incorrectly, see the second heading below ("To combine all distinct Tshirt instances together") for my original, irrelevant, answer)
To combine all Tshirt instances and sum their qtys:
I see you're using a tuple of color + size to uniquely identify a type of t-shirt, which means if we combine all Tshirt instances together (Concat), then group them by color + size, then Sum the qty values, then return new Tshirt instances in a new list.
List<Tshirt> aggregatedShirts = uniqueShirts = Enumerable
.Empty<Tshirt>()
.Concat( list1 )
.Concat( list2 )
.GroupBy( shirt => new { shirt.Color, shirt.size } )
.Select( grp => new Tshirt()
{
Color = grp.Key.Color,
size = grp.Key.size,
qty = grp.Sum( shirt => shirt.qty )
} )
.ToList();
To combine all distinct Tshirt instances together
Assuming class Tshirt implements IEquatable<Tshirt> then just use Concat( ... ).Distinct().ToList():
I'd do it this way, others might prefer not to use Empty:
List<Tshirt> uniqueShirts = Enumerable
.Empty<Tshirt>()
.Concat( list1 )
.Concat( list2 )
.Distinct()
.ToList();
If Tshirt does not implement IEquatable then you can use the overload of Distinct that accepts an IEqualityComparer<TSource>:
class TshirtComparer : IEqualityComparer<Tshirt>
{
public static TshirtComparer Instance { get; } = new TshirtComparer();
public Boolean Equals(Tshirt x, Tshirt y)
{
if( ( x == null ) != ( y == null ) ) return false;
if( x == null ) return true;
return x.Color == y.Color && x.size == y.size && x.qty == y.qty;
}
public Int32 GetHashCode(Tshirt value)
{
if( value == null ) return 0;
// See https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
Int32 hash = 17;
hash = hash * 23 + value.Color?.GetHashCode() ?? 0;
hash = hash * 23 + value.size?.GetHashCode() ?? 0;
hash = hash * 23 + value.qty;
return hash;
}
}
Usage:
List<Tshirt> uniqueShirts = Enumerable
.Empty<Tshirt>()
.Concat( list1 )
.Concat( list2 )
.Distinct( TshirtComparer.Instance )
.ToList();
Then to get the total quantity:
Int32 totalQuantity = uniqueShirts.Sum( shirt => shirt.qty );

var list3 = list1.Union(list2).GroupBy(o => new {o.Color, o.size})
.Select(o => new Tshirt()
{
Color = o.Key.Color,
size = o.Key.size,
qty = o.Sum(q => q.qty)
}).OrderByDescending(o => o.qty).ToList();

Related

Combining values of two dictionaries in C# with distinct keys

I am having difficulty combining two dictionaries into a dictionary with two values combined to a list for identical keys. For example, having D1 and D2
D1 = {2:"a",
3:"b",
4: "c"}
D2 = {1:"e",
2:"f",
4:"h",
5:"i"}
I would like to create D3.
D3= { 1:["", "e"]
2:["a", "f"]
3:["b", ""]
4:["c":"h"]
5:["", "i"]}
Thank you.
This can be done in a single Linq expression like so:
Flatten and concatenate both d1 and d2 to a single flat sequence of (Int32,String) value-tuples.
Re-group them by the Int32 key (this is the main step).
Then convert each group into a separate output dictionary entry.
Dictionary<Int32,String> d1 = new Dictionary<Int32,String>()
{
{ 2, "a" },
{ 3, "b" },
{ 4, "c" },
};
Dictionary<Int32,String> d2 = new Dictionary<Int32,String>()
{
{ 1, "e" },
{ 2, "f" },
{ 4, "h" },
{ 5, "i" },
};
Dictionary<Int32,List<String>> d3 = Array
.Empty<( Int32 k, String v )>()
// Step 1:
.Concat( d1.Select( kvp => ( k: kvp.Key, v: kvp.Value ) ) )
.Concat( d2.Select( kvp => ( k: kvp.Key, v: kvp.Value ) ) )
// Step 2:
.GroupBy( t => t.k )
// Step 3:
.ToDictionary(
grp => grp.Key,
grp => grp.Select( t => t.v ).OrderBy( v => v ).ToList()
);
An advantage of this approach is that it works for any number of duplicated values (not just two). Also, the use of ValueTuple means this approach should have fewer heap-allocations.
Screenshot proof of it working in LinqPad:
The expression can be made more succint - I use a more verbose style myself, but if you want to be cryptic about it by re-using KeyValuePair instead of ValueTuple, and if you don't care about ordering, then you can do this:
var d3 = d1
.Concat( d2 )
.GroupBy( kvp => kvp.Key )
.ToDictionary( g => g.Key, g => g.Select( kvp => kvp.Value ).ToList() );
Simplest solution would be with Dictionary.Keys
var D1 = new Dictionary<int,string>(){{2,"a"}, {3,"b"},{4,"c"}};
var D2 = new Dictionary<int,string>(){{1,"e"},{2,"f"}, {4,"h"},{5,"i"}};
var keys = D1.Keys.Union(D2.Keys).OrderBy(key => key);
var test = keys.Select(key => new {Key = key, Value= new string[] {D1.ContainsKey(key) ? D1[key] : "", D2.ContainsKey(key) ? D2[key] : ""} });
Console.WriteLine(test);
Interactive: https://rextester.com/UXQ51844
Alternatively, you could do something similar to this: LINQ - Full Outer Join
Sounds to be a job for LINQ. Here is one possibility to solve this issue:
public class Element
{
public int Index { get; set; }
public string Value { get; set; }
}
public class GroupedElement
{
public int Index { get; set; }
public IReadOnlyList<string> Values { get; set; }
}
public static class Program
{
public static void Main(string[] args)
{
var d1 = new[]
{
new Element { Index = 2, Value = "a" },
new Element { Index = 3, Value = "b" },
new Element { Index = 4, Value = "c" },
};
var d2 = new[]
{
new Element { Index = 1, Value = "e" },
new Element { Index = 2, Value = "f" },
new Element { Index = 4, Value = "h" },
new Element { Index = 5, Value = "i" },
};
var result = d1.Concat(d2)
.GroupBy(element => element.Index)
.Select(group => new GroupedElement { Index = group.Key, Values = group.Select(g => g.Value).ToList() })
.ToList();
foreach (var item in result)
{
Console.WriteLine($"{item.Index}: {string.Join(",", item.Values)}");
}
}
}
I think this is simpler without LINQ (LINQ is a hammer, not every problem is a nail)
Let's loop from 1 to 5, putting a new List for each int. The list is inited with d1's value and d2's value
var d3 = new Dictionary<int, List<string>>();
for(int x=1;x<6;x++)
d3[x] = new() { d1.GetValueOrDefault(x,""), d2.GetValueOrDefault(x,"") };
If your ints aren't always contiguous you could (use a bit of LINQ 😀 and..)
foreach(int x in d1.Keys.Union(d2.Keys))
d3[x] = new() { d1.GetValueOrDefault(x,""), d2.GetValueOrDefault(x,"") };
This doesn't need another answer the others answers are plenty good enough and well done, however here is another (convoluted) approach
Given
var d1 = new Dictionary<int, string> {{2, "a"}, {3, "b"}, {4, "c"}};
var d2 = new Dictionary<int, string> { { 1, "e" }, { 2, "f" }, { 4, "h" }, { 5, "i" } };
Usage
static string[] Stuff((string, string)[] v) =>
new[] {v[0].Item1 ?? v.ElementAtOrDefault(1).Item1 ?? "", v[0].Item2 ?? v.ElementAtOrDefault(1).Item2 ?? "" };
var result = d1
.Select(x => (x.Key, (x.Value,(string)null)))
.Concat(d2.Select(x => (x.Key, ((string)null, x.Value ))))
.GroupBy(element => element.Key)
.ToDictionary(x => x.Key, x => Stuff(x.Select(y =>y.Item2).ToArray()))
Output
foreach (var item in result.OrderBy(x => x.Key))
Console.WriteLine($"{item.Key}: {string.Join(",", item.Value)}");
---
1: ,e
2: a,f
3: b,
4: c,h
5: ,i
Please see, here is another approach for this query -
Input -
Dictionary<int, string> first_dict = new Dictionary<int, string>()
{
{ 2,"a" },
{ 3,"b" },
{ 4, "c"}
};
Dictionary<int, string> second_dict = new Dictionary<int, string>()
{
{ 1,"e" },
{ 2,"f" },
{ 4, "h"},
{ 5, "i"}
};
First, I got common keys from both dictionaries like this -
var allKeys = first_dict.Concat(second_dict).OrderBy(b => b.Key).Select(b => b.Key).Distinct().ToList();
and then I created two another dictionaries and inserted data into them like this -
Dictionary<int, string> first_dict_res = new Dictionary<int, string>();
Dictionary<int, string> second_dict_res = new Dictionary<int, string>();
foreach (var keyItem in allKeys)
{
var first_dict_res_value = (first_dict.ContainsKey(keyItem)) ? first_dict[keyItem] : null;
first_dict_res.Add(keyItem, first_dict_res_value);
var second_dict_res_value = (second_dict.ContainsKey(keyItem)) ? second_dict[keyItem] : null;
second_dict_res.Add(keyItem, second_dict_res_value);
}
and then I concatenated the result from both dictionaries to get the desired result-
var res_dict = first_dict_res.Concat(second_dict_res).GroupBy(b => b.Key)
.Select(c => new { key = c.Key, values = string.Join(",", c.Select(b => b.Value)) }).ToList();

How to progressively build a group by Linq query?

Suppose I have the items
{ // item 0
Color = yellow,
Priority = high,
},
{ // item 1
Color = yellow,
Priority = medium,
},
{ // item 2
Color = green,
Priority = high,
},
I want to be able to progressively build a GroupBy query as using var grouped = items.GroupBy(item => item.Color), what in this case I would have 2 groups and then group again using by the key item.Priority to have 3 groups.
Unfortunately using var regrouped = grouped.GroupBy(item => item.Priority) is not a valid solution.
The final result must be equivalent as doing
items.GroupBy(item => new {item.Color, item.Priority});
Since you want to regroup on a subkey as a new object, you can use ToLookup to create the IGroupings you need, and SelectMany to flatten them into the new IEnumerable:
var regrouped = grouped.SelectMany(cg => cg.GroupBy(i => i.Priority)
.ToLookup(pg => new { Color = cg.Key, Priority = pg.Key },
pg => pg.Select(i => i)
)
);
If I understood you correctly, you want to group each group of Color into Priority. If that's the case, this should work:
var items = new List<Item>
{
new Item { Color = "yellow", Priority = "high" },
new Item { Color = "red", Priority = "high" },
new Item { Color = "yellow", Priority = "medium" },
new Item { Color = "red", Priority = "medium" },
new Item { Color = "green", Priority = "high" },
new Item { Color = "green", Priority = "high" },
new Item { Color = "red", Priority = "high" },
};
var groupped = items.GroupBy(x => x.Color);
var regroupped = groupped.Select(x => new
{
Color = x.Key,
Priorities = x.GroupBy(y => y.Priority)
});
Notice that this returns the same result set than your query
var regroupped = items.GroupBy(item => new {item.Color, item.Priority});

Combining lists in linq

in linq, is it possible to combine many lists (of the same type), such that two lists,
list 1 = {a,b,c} and list 2 = {x,y,z}
turns into {[1,a] , [1,b] , [1,c] , [2,x] , [2,y] , [2,z] }
where [] represents a pair containing a "list identifier"
The problem is from having decks of arbitrary cards, where each deck is a list in a collection of lists.
I'm trying to create a query such that I can select only cards in a certain deck, or cards similar to 2 or more decks.
This is probably a duplicate question, but I don't know how to search for the question further then I already have.
List<List<int>> lists;
var combined = lists.Select((l, idx) => new { List = l, Idx = idx })
.SelectMany(p => p.List.Select(i => Tuple.Create(p.Idx + 1, i)));
var list1 = new List<string>() {a,b,c};
var list2 = new List<string>() {x,y,z};
var combined = list1.Select(x => new { id = 1, v = x }).Concat(list2.Select(x => new { id = 2, v = x }));
Normally I'd suggest Enumerable.Zip for combining multiple lists, however you seem to actually want to concatenate multiple lists with a list counter.
public IEnumerable<Tuple<int,T>> Combine<T>(params IEnumerable<T>[] lists) {
return lists.Select((x,i) => x.Select(y => Tuple.Create(i+1,y))).SelectMany (l =>l);
}
UPDATE
Completely missed that SelectMany has the index option so the above code can be written as
public IEnumerable<Tuple<int,T>> Combine<T>(params IEnumerable<T>[] lists) {
return lists.SelectMany((x,i) => x.Select(y => Tuple.Create(i+1,y)));
}
Then you can do
var list1 = new List<string> { "a", "b", "c" };
var list2 = new List<string> { "x", "y", "z" };
var combined = Combine(list1,list2);
Combined will be enumerable of tuples, with Item1 being the list index identifier (starting at 1) and Item2 being the value.
This method will handle multiple lists so you could just as easily call it with:
var list3 = new List<string> { "f", "g" };
var combined = Combine(list1,list2,list3);
You can merge the lists like:
var first = new List<string> {"a","b","c"};
var second = new List<string> {"x","y","z"};
var merged = first.Select(item => new { ListIndex = 1, Value = item}).ToList();
merged.AddRange(second.Select(item => new { ListIndex = 2, Value = item});
//or use concat
var merged = first.Select(item => new { ListIndex = 1, Value = item});
.Concat(second.Select(item => new { ListIndex = 2, Value = item});
Alternatively if you have the sources in something like:
List<List<string>> lists = new List<List<string>>
{
new List<string> {"a","b","c"},
new List<string> {"x","y","z"}
};
you can do:
var merged = lists.SelectMany((item, index) =>
item.Select(s => new { ListIndex = index, Value = s}));
Note that this will produce a 0-based list, so if you really need a 1-base list, just do ListIndex = index +1.
Also, if you will use this a lot, I would create it as an specific entity, something like
struct ListIdentValue
{
public int ListIndex {get; private set;}
public string Value {get; private set;}
public ListIdentValue(int listIndex, string value) {...}
}
Try using Concat
new[] {'a','b','c'}
.Select(v=>new Tuple<int,char>(1, v))
.Concat(
new[] {'x','y','z'}.Select(v=>new Tuple<int,char>(2, v))
)
string[] a = { "a", "b", "c" };
string[] b = { "x", "z", "y" };
var t =
(
from ai in a
select new { listNo = 1, Item = ai }
).Union
(
from bi in b
select new { listNo = 2, Item = bi }
);
or
var t =
(
from ai in a
select new object[] { 1, ai }
).Union
(
from bi in b
select new object[] { 2, bi }
);

C# Linq Union On Attribute

I have two linq queries that I want to unionize on a common attribute:
One
{
Id,
Name,
Color
}
Two
{
Color,
Cost
}
I want to get the union of One and Two by unionizing on Color? If there is not a Two with a Color that corresponds to One, I want to set Cost to 0 in the output? How do I do this in LINQ?
Here is a sample using anonymous types on how to perform a left outer join:
var products = new[] {
new { Id = 1, Name = "Alpha", Color = "Red" },
new { Id = 2, Name = "Beta", Color = "Green" },
new { Id = 3, Name = "Gamma", Color = "Blue" }
};
var costs = new[] {
new { Color = "Red", Cost = 100 },
new { Color = "Blue", Cost = 200 },
new { Color = "Blue", Cost = 300 }
};
var query = products
.GroupJoin(
costs, p => p.Color, c => c.Color,
(p, c) => new { p.Id, p.Name, p.Color, Costs = c.DefaultIfEmpty() }
)
.SelectMany(
gj => gj.Costs,
(gj, c) => new { gj.Id, gj.Name, gj.Color, Cost = c == null ? 0 : c.Cost }
);
Query result:
Id Name Color Cost
-------------------
1 Alpha Red 100
2 Beta Green 0
3 Gamma Blue 200
3 Gamma Blue 300
This is called a join, not a union.
See the documentation.
You want a left outer join to keep the values appearing in the first list but are not present in the second.

Calculate all possible pairs of items from two lists?

I have two arrays:
string[] Group = { "A", null, "B", null, "C", null };
string[] combination = { "C#", "Java", null, "C++", null };
I wish to return all possible combinations like:
{ {"A","C#"} , {"A","Java"} , {"A","C++"},{"B","C#"},............ }
The null should be ignored.
Group.Where(x => x != null)
.SelectMany(g => combination.Where(c => c != null)
.Select(c => new {Group = g, Combination = c})
);
Alternatively:
from g in Group where g != null
from c in combination where c != null
select new { Group = g, Combination = c }

Categories

Resources