In my code below I would like to get Invoices with their aggregate InvoiceLine totals and also a list of Tracks associated with each Invoice.
var screenset =
from invs in context.Invoices
join lines in context.InvoiceLines on invs.InvoiceId equals lines.InvoiceId
join tracks in context.Tracks on lines.TrackId equals tracks.TrackId
group new { invs, lines, tracks }
by new
{
invs.InvoiceId,
invs.InvoiceDate,
invs.CustomerId,
invs.Customer.LastName,
invs.Customer.FirstName
} into grp
select new
{
InvoiceId = grp.Key.InvoiceId,
InvoiceDate = grp.Key.InvoiceDate,
CustomerId = grp.Key.CustomerId,
CustomerLastName = grp.Key.LastName,
CustomerFirstName = grp.Key.FirstName,
CustomerFullName = grp.Key.LastName + ", " + grp.Key.FirstName,
TotalQty = grp.Sum(l => l.lines.Quantity),
TotalPrice = grp.Sum(l => l.lines.UnitPrice),
Tracks = grp.SelectMany(t => t.tracks)
};
However, in the last line were I did a SelectMany is giving me an error:
Tracks = grp.SelectMany(t => t.tracks)
Error:
The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.
Any ideas why?
Thanks in advance.
Object tracks is a single track and not a List. If you need to use SelectMany, use need to select a list in order to :
Projects each element of a sequence to an IEnumerable and flattens
the resulting sequences into one sequence.
So Change it to:
Tracks = grp.Select(t => t.tracks)
The real usage of SelectMany, is when you have a List of Lists and you want to convert the Lists into a single list. Example:
List<List<int>> listOfLists = new List<List<int>>()
{
new List<int>() { 0, 1, 2, 3, 4 },
new List<int>() { 5, 6, 7, 8, 9 },
new List<int>() { 10, 11, 12, 13, 14 }
};
List<int> selectManyResult = listOfLists.SelectMany(l => l).ToList();
foreach (var r in selectManyResult)
Console.WriteLine(r);
Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Related
var subset = new[] { 9, 3, 9 };
var superset = new[] { 9, 10, 5, 3, 3, 3 };
subset.All(s => superset.Contains(s))
This code would return true, because 9 is included in the superset,but only once, I want an implementation that would take into account the duplicates, so it would return false
My thought was that you could group both sets by count, then test that the super group list contained every key from the sub group list and, in each case, the super count was greater than or equal to the corresponding subcount. I think that I've achieved that with the following:
var subset = new[] { 9, 3, 9 };
var superset = new[] { 9, 10, 5, 3, 3, 3 };
var subGroups = subset.GroupBy(n => n).ToArray();
var superGroups = superset.GroupBy(n => n).ToArray();
var basicResult = subset.All(n => superset.Contains(n));
var advancedResult = subGroups.All(subg => superGroups.Any(supg => subg.Key == supg.Key && subg.Count() <= supg.Count()));
Console.WriteLine(basicResult);
Console.WriteLine(advancedResult);
I did a few extra tests and it seemed to work but you can test some additional data sets to be sure.
Here is another solution :
var subset = new[] { 9, 3, 9 };
var superset = new[] { 9, 10, 5, 3, 3, 3 };
var subsetGroup = subset.GroupBy(x => x).Select(x => new { key = x.Key, count = x.Count() });
var supersetDict = superset.GroupBy(x => x).ToDictionary(x => x.Key, y => y.Count());
Boolean results = subsetGroup.All(x => supersetDict[x.key] >= x.count);
This works for me:
var subsetLookup = subset.ToLookup(x => x);
var supersetLookup = superset.ToLookup(x => x);
bool flag =
subsetLookup
.All(x => supersetLookup[x.Key].Count() >= subsetLookup[x.Key].Count());
That's not how sets and set operations work. Sets cannot contain duplicates.
You should treat the two arrays not as sets, but as (unordered) sequences. A possible algorithm would be: make a list from the sequence superset, then remove one by one each element of the sequence subset from the list until you are unable to find such an element in the list.
bool IsSubList(IEnumerable<int> sub, IEnumerable<int> super)
{
var list = super.ToList();
foreach (var item in sub)
{
if (!list.Remove(item))
return false; // not found in list, so sub is not a "sub-list" of super
}
return true; // all elements of sub were found in super
}
var subset = new[] { 9, 3 };
var superset = new[] { 9, 10, 5, 3,1, 3, 3 };
var isSubSet = IsSubList(subset, superset);
I have an array of lists:
private List<int>[] Graph = new List<int>[n];
For example:
Graph[0] = new List<int>() { 1, 2 };
Graph[1] = new List<int>() { 0 };
Graph[2] = new List<int>() { 0, 1, 3, 4 };
Graph[3] = new List<int>() { 2, 4, 1 };
Graph[4] = new List<int>() { 2, 3 };
Graph[0].Count // give 2
Graph[1].Count // give 1
Graph[2].Count // give 4
Graph[3].Count // give 3
Graph[4].Count // give 2
And I want to get an array (or list) which includes the indexes of the lists sorted by the count of the elements in each list. So for this example it will be:
orderList[0] -> 2 //(because Graph[2].Count give 4)
orderList[1] -> 3 //(because Graph[3].Count give 3)
orderList[2] -> 0 //(because Graph[0].Count give = 2)
orderList[3] -> 4 //(because Graph[4].Count give = 2)
orderList[4] -> 1 //(because Graph[1].Count give = 1)
orderList is an n-elements array.
You can use the select method that incorporates an index to combine the list count with the index
int[] orderList = Graph.Select((list, index) => new { Count = list.Count, Index = index }).OrderByDescending(a => a.Count).Select(a => a.Index).ToArray();
More readable query syntax
int[] orderList = (from pair in Graph.Select((list, index) => new { Count = list.Count, Index = index })
orderby pair.Count descending
select pair.Index).ToArray();
All you need is:
Graph = Graph.OrderByDescending(x => x.Count).ToArray();
You can use LINQ:
List<int>[] orderedGraph = graph.OrderByDescending(x => x.Count).ToArray();
This will order array descending using list "count" property.
Remember to add using:
using System.Linq;
Suppose I have a "database" defined as:
// Baked goods vendors
var vendor = new[] {
new { ID = 1, Baker = "Pies R Us", StMnemon = "NY", Items = 8, Rating = 9 },
new { ID = 2, Baker = "Mikes Muffins", StMnemon = "CA", Items = 5, Rating = 9 },
new { ID = 3, Baker = "Best Bakers", StMnemon = "FL", Items = 2, Rating = 5 },
new { ID = 4, Baker = "Marys Baked Treats", StMnemon = "NY", Items = 8, Rating = 7 },
new { ID = 5, Baker = "Cool Cakes", StMnemon = "NY", Items = 4, Rating = 9 },
new { ID = 6, Baker = "Pie Heaven", StMnemon = "CA", Items = 12, Rating = 9 },
new { ID = 7, Baker = "Cakes N More", StMnemon = "GA", Items = 6, Rating = 8 },
new { ID = 8, Baker = "Dream Desserts", StMnemon = "FL", Items = 2, Rating = 7 }
};
// Locations
var location = new[] {
new {ID= 1, State = "New York", Mnemonic = "NY"},
new {ID= 2, State = "Massachusetts", Mnemonic = "MA"},
new {ID= 3, State = "Ohio", Mnemonic = "OH"},
new {ID= 4, State = "California", Mnemonic = "CA"},
new {ID= 5, State = "Florida", Mnemonic = "FL"},
new {ID= 6, State = "Texas", Mnemonic = "TX"},
new {ID= 7, State = "Georgia", Mnemonic = "GA" }
};
I want to build a query that would be the equivalent of the SQL query:
SELECT State, Rating, SUM(Items) AS 'Kinds'
FROM vendor, location
WHERE vendor.StMnemon = location.Mnemonic
GROUP BY State, Rating
Two things of interest in this query are:
The GROUP BY involves multiple tables, and
The result contains a summation of a column not appearing in the grouping criteria.
I've seen the solutions in the posts on grouping by multiple tables and summing columns not in the group-by. The problem is that combining both doesn't really duplicate the relational query.
I try to duplicate it in LINQ with the following code:
var query = from v in vendor
join l in location
on v.StMnemon equals l.Mnemonic
orderby v.Rating ascending, l.State
select new { v, l };
var result = from q in query
group q by new {
s = q.l.State,
r = q.v.Rating
/* ==> */ , i = q.v.Items
} into grp
select new
{
State = grp.Key.s,
Rating = grp.Key.r
/* ==> */ , Kinds = grp.Sum(k => grp.Key.i)
};
This results in:
=================================
State Rating Kinds
Florida 5 2
Florida 7 2
New York 7 8
Georgia 8 6
California 9 5
California 9 12
New York 9 8
New York 9 4
=================================
Whereas, the SQL query given above gives this result:
=========================
State Rating Kinds
Florida 5 2
Florida 7 2
New York 7 8
Georgia 8 6
California 9 17
New York 9 12
=========================
The discrepancy is because there seems to be no place to put additional columns, other than in the grouping criteria, which of course changes the grouped result. Commenting out the two lines indicated by the /* ==> */ comment in the code above will give the same grouping as the SQL result, but of course that removes the summation field that I want to include.
How do we group multiple tables in LINQ and include additional criteria without changing the grouped result?
something like this seems to return the same as the SQL query:
var result = from v in vendor
from l in location
where l.Mnemonic == v.StMnemon
group v by new { l.State, v.Rating } into grp
orderby grp.Key.Rating ascending, grp.Key.State
select new {State = grp.Key.State, Rating = grp.Key.Rating, Kinds = grp.Sum(p=>p.Items)};
foreach (var item in result)
Console.WriteLine("{0}\t{1}\t{2}", item.State, item.Rating, item.Kinds);
You can do an aggregation outside of the group:
var query = from v in vendor
join l in location
on v.StMnemon equals l.Mnemonic
orderby v.Rating ascending, l.State
select new { v, l };
var result = from q in query
group q by new {
s = q.l.State,
r = q.v.Rating
} into grp
select new
{
State = grp.Key.s,
Rating = grp.Key.r,
Kinds = grp.Sum(g => g.Items)
};
Grouping is a little tricky to grasp - it returns an IGrouping that has one property - Key. The actual items in that grouping are returned by the GetEnumerator() function that lets you treat the group as a collection of those items, meaning you can do aggregation on the items within that group.
I have a list using this Linq query
filterEntities = (from list in filterEntities where list.Id== 0 && list.Id== 1 && list.Id == 3 && list.Id== 6 select list).OrderBy(r => r.Id).ToList();
Now this linq returns a list like
ID Age
0 18
0 19
1 21
3 24
6 32
6 08
I want to generate a list using sum of same Id's which returns like
ID Age
0 37
1 21
3 24
6 40
Please suggest me possible query
I think you are looking to use a group by like this
List<int> ids = new List<int>() { 0, 1, 3, 6 };
filterEntities = (from list in filterEntities
where ids.Contains(list.Id)
group list by list.id into g
orderby g.Key
select new
{
ID = g.Key,
Age = g.Sum(x => x.Age),
}).ToList();
I would clean up the query like this, because the long expression looks a bit confusing:
var idList = new List<int> { 0, 1, 3, 6};
filterEntities = from e in filterEntities
where idList.Contains(e.Id)
group e by e.Id into g
select new { Id = g.Key, Sum = g.Sum(e =>e.Age) };
filterEntities = filterEntities.Where(l=>new[] { 0, 1, 3, 6 }.Contains(l.Id))
.Sum(c=>c.Age)
.GroupBy(r=>r.Id)
.ToList();
This might be either impossible or so obvious I keep passing over it.
I have a list of objects(let's say ints for this example):
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
I'd like to be able to group by pairs with no regard to order or any other comparison, returning a new IGrouping object.
ie,
list.GroupBy(i => someLogicToProductPairs);
There's the very real possibility I may be approaching this problem from the wrong angle, however, the goal is to group a set of objects by a constant capacity. Any help is greatly appreciated.
Do you mean like this:
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
IEnumerable<IGrouping<int,int>> groups =
list
.Select((n, i) => new { Group = i / 2, Value = n })
.GroupBy(g => g.Group, g => g.Value);
foreach (IGrouping<int, int> group in groups) {
Console.WriteLine(String.Join(", ", group.Select(n=>n.ToString()).ToArray()));
}
Output
1, 2
3, 4
5, 6
you can do something like this...
List<int> integers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var p = integers.Select((x, index) => new { Num = index / 2, Val = x })
.GroupBy(y => y.Num);
int counter = 0;
// this function returns the keys for our groups.
Func<int> keyGenerator =
() =>
{
int keyValue = counter / 2;
counter += 1;
return keyValue;
};
var groups = list.GroupBy(i => {return keyGenerator()});