foreach to linq expression help needed - c#

having some trouble writing the following code to some nicer/less lines :)
any one have the good solution?
//custom implementation for popular filters
var popularFilter = new Dictionary<string, int>();
foreach (var car in allFilteredCars)
{
foreach (var offering in car.Offerings)
{
if (popularFilter.ContainsKey(offering))
popularFilter[offering] = popularFilter[offering] + 1;
else
popularFilter.Add(offering, 1);
}
}
categories.Add(new Category
{
Name = "popular",
Code = "popular",
Values = popularFilter.Select(p => new Value
{
Code = p.Key,
Name = p.Key,
Count = p.Value
}).ToList()
});
If it is possible i want i directly to add it in the categories list.
car.offerings = list<string>
so basicly something like:
Categories.Add(allFilteredCars.SelectMany(
c => c.Offerings.Select(
o => new {
something magical here}
.Select(a =>
new Category{
code.. etc etc..}
));

It looks like you just want to do a SelectMany to get the offerings, then group them and select the Count.
categories.Add(new Category
{
Name = "popular",
Code = "popular",
Values = allFilteredCars.SelectMany(c => c.Offerings)
.GroupBy(o => o)
.Select(grp => new Value
{
Code = grp.Key,
Name = grp.Key,
Count = grp.Count()
}).ToList()
});

Your non linq code already looks quite fine.
You can create your dictionary with linq by using a GroupBy & ToDictionary:
var dictionary = offerings
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());

Related

String concatenation in GroupBy

This query below doesn't work because String.Join is not translatable.
PostgreSQL has the string_agg(expression, delimiter) feature though.
Is there anyway to use it from Linq?
var vwTourWithCategorieses = Context.Tours
.Join(Context.TourCategories, t => t.TourId, tc => tc.TourId,
(t, tc) => new { t.TourId, t.Name, tc.CategoryId})
.Join(Context.Categories, x => x.CategoryId, c => c.CategoryId,
(x, c) => new { x.TourId, TourName = x.Name, CategoryName = c.Name})
.GroupBy(x => new { x.TourId, x.TourName },
(key, c) => new VwTourWithCategories
{
TourId = key.TourId,
Name = key.TourName,
Categories = string.Join(",", c.Select(i => i.CategoryName))
})
.ToList();
Yes, unfortunately String.Join is not supported by EF, but I think you could project the result that you expect using Linq to objects after you materialize your query:
var query= Context.Tours
.Join(Context.TourCategories, t => t.TourId, tc => tc.TourId,
(t, tc) => new { t.TourId, t.Name, tc.CategoryId})
.Join(Context.Categories, x => x.CategoryId, c => c.CategoryId,
(x, c) => new { x.TourId, TourName = x.Name, CategoryName = c.Name})
.GroupBy(x => new { x.TourId, x.TourName }).ToList()
var result=query.Select( g=> new VwTourWithCategories
{
TourId = g.Key.TourId,
Name = g.Key.TourName,
Categories = string.Join(",", g.Select(i => i.CategoryName))
});
If you want to see all the CLR methods that are supported, you can check this link.
Update
Your query could be simpler if you use navigation properties. I think that is a many to many relationship, so you could do something like this:
var query= Context.Tours.Select(t=> new
{
t.TourId,
t.Name,
CategoryNames = t.TourCategories.Select(tc=>tc.Category.Name)
}
).ToList();
var result=query.Select( g=> new VwTourWithCategories
{
TourId = g.Key.TourId,
Name = g.Key.TourName,
Categories = string.Join(",", g.Select(i => i.CategoryName))
});

create n lists of list linq

I have a simple list
var list =
AppUtils.db.GetDataTable("dbo.RankSelectChart", view) // stopred procedure and getting datatable
.AsEnumerable()
.Select(i => new
{
Date = i.Field<DateTime>("lastDatetime"),
P1 = i.Field<decimal>("p1"),
P2 = i.Field<decimal>("P2"),
P3..... P(n)
}
)
.ToList()
.OrderBy(x => x.Date);
than i want to get a list of lists or dictionary like List<Dictionary<Datetime, Decimal>> means Dictionary<Date, P1> .... Dictionary<Date, P(n)>
how to write algorithm which is not depend how many P we have
As it stands, you will need to use reflection to access the properties:
var result = new[]{"P1", "P2", "P3", ...}.Select(p => list.ToDictionary(
i => i.Date,
i => i.GetType().GetProperty(p).GetValue(i)));
However, if you could avoid creating your list in the first place and just pull from the data table directly, it may be easier.
var dt = AppUtils.db.GetDataTable("dbo.RankSelectChart", view); // stopred procedure and getting datatable
var pColumns = dt.Columns.Cast<DataColumn>()
.Where(c => c.ColumnName.StartsWith("p"));
var result = pColumns
.Select(p => dt.AsEnumerable().ToDictionary(
i => i.Field<DateTime>("lastDatetime"),
i => i.Field<DateTime>(p.ColumnName)))
.ToList();
If 'Date' is unique for all records in 'list', then you can use reflection to get the P(i) value for a record in list. Like so:
// build sample data
var list = Enumerable.Range(0, 10)
.ToList()
.Select(x => new {
Date = DateTime.Now.AddMinutes(x),
P1 = new Decimal(x),
P2 = new Decimal(x + 1),
P3 = new Decimal(x + 2)
})
.ToList();
// list partionned by date; assumes that Date is unique in list
List<Dictionary<DateTime, Decimal>> partitionedList;
if (list.Count == 0) {
partitionedList = new List<Dictionary<DateTime, Decimal>>();
} else {
var n = 3;
var listElementType = list[0].GetType();
partitionedList = Enumerable.Range(1, n)
.Select(x => {
var prop = listElementType.GetProperty("P" + x);
var pList = list.ToDictionary(
ll => ll.Date,
ll => (Decimal)prop.GetValue(ll));
return pList;
})
.ToList();
}
If 'Date' is not unique, then it cannot be the key to a dictionary and the desired data structure is not achievable.

Concatinating properties in a list of items

I am having trouble with a small section of code.
I have a List of a MapItem class with a couple properties, Address and Html, and I need to concatenate the Html properties for each item with an identical Address property
For example:
firstMapItem = new MapItem { Address = "1122 Elm Street",
Html="<p>some html</p>" };
secondMapItem = new MapItem { Address = "1122 Elm Street",
Html="<p>different html</p>" };
would become:
firstMapItem.Address == "1122 Elm Street";
firstMapItem.Html == "<p>some html</p><p>different html</p>";
secondMapItem.Address == "1122 Elm Street";
secondMapItem.Html == "<p>some html</p><p>different html</p>";
This is what I have tried so far:
foreach (MapItem item in mapItems)
{
var sameAddress = from m in mapItems
where m.Address == item.Address
select m;
if (sameAddress.Count() > 1)
{
//tried inserting -> item.Html = ""; right here as well
foreach (MapItem single in sameAddress)
{
item.Html += single.Html;
}
}
}
I am probably making this more complicated than it needs to be.
Thanks in advance.
You could group by Address and then concatenate the Html values:
var results = from m in mapItems
group m by m.Address into ms
select new MapItem
{
Address = ms.Key,
Html = string.Concat(ms.Select(m => m.Html))
};
Use a grouping on the address, then just string.Join the Html of all the items in the group to produce a new MapItem:
var resultList = mapItems.GroupBy(m => m.Address)
.Select(g => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) })
.ToList();
Edit:
Like the other solutions presented so far above approach will remove duplicates - that doesn't seem to be what you want - below a solution that creates a list that is not deduplicated (so will produce 2 items for the sample input)
var resultList = mapItems.GroupBy(m => m.Address)
.Select(g => g.Select( item => new MapItem() { Address = g.Key, Html = string.Join("", g.Select(x => x.Html)) } ))
.SelectMany( x=> x)
.ToList();
If you group by Address, you'll end up with only one item when you have items with the same Address. If that's OK with, go with Group By. However, if you need all the original items, with the Html concatenated, you should do like that:
var newMapItems = mapItems
.Select(mi => new MapItem() { Address = mi.Address,
Html = mapItems.Where(mi2 => mi2.Address == mi.Address)
.Select(mi3 => mi3.Html)
.Aggregate((acc, html) => acc += html)
}
);
You can do this with a GroupBy and Select:
var result = items
.GroupBy(m => m.Address, m => m.Html)
.Select(g => new MapItem() {Address = g.Key, Html = string.Concat(g.Select(h => h))});
This code should update your existing objects with appended values.
foreach (MapItem item in mapItems)
{
var sameAddress = from m in mapItems
group m by m.Address into ms
select string.Join("", ms.Select(e => e.Html).ToArray());
foreach (string concatHtml in sameAddress)
{
item.Html = concatHtml;
}
}

Linq nhibernate groups and joins

Consider a simple order example (should get the title and quantity ordered for each product):
(note - grouping by Title is not a good answer)
var orderQuery =
session.Query<OrderLine>()
.Where(ol => ol.Quantity > 0)
.GroupBy(ol => ol.Product.Id)
.Select(x => new
{
productId = x.Key,
quantity = x.Sum(i => i.Quantity)
});
var query =
session.Query<Product>()
.Join(orderQuery,
x => x.Id,
x => x.productId,
(x, p) => new { x.FeedItem.Title, p.quantity });
However, this throws a
could not resolve property: Key of: OrderLine
any ideas?
Try to create your query using QueryOver and Projections
Sample

GroupBy with multiple groups as a hierarchy

I am using GroupBy create a hierarchical set of groups to use in multiple child grids.
Assume I have a query with with 6 columns, a, b, c, d, e, f.
Now, I need to group by a, then by b, then by c. and return the entire row in the group of c's.
var q = rows.GroupBy(x => x.a)
Ok, that's nice. That gives me my group of a's. Next, we look to group them by a and b.
var q1 = q.Select(g =>new {
Key = g.Key,
SubGroup = g.GroupBy(x => x.b)
}
Ok, that also works nice. I get my group of a's with subgroups of b's.
Now I'm stumped at the third level. I've tried various syntaxes, but most won't even compile. The ones that do do not give the correct results.
var q2 = q1.Select(g1 => new {
Key = g1.Key,
SubGroup = g1.GroupBy(x => x.c)
}
This doesn't compile. Tells me that there is no GroupBy on g1.
var q2 = q.Select(g1 => new {
Key = g1.Key,
SubGroup = g1.GroupBy(x => x.c)
}
This doesn't give me the b subgroup, only the a and c.
Any idea of what i'm doing wrong here?
EDIT:
The Following also does not work, saying there is no definition for the g1.Key
var q2 = q.Select(g => new {
Key = g.Key,
SubGroup = g.Select(g1 => new {
Key = g1.Key
SubGroup = g1.GroupBy(a => a.c)
})
I have such a poor grasp on what this is doing internally.
Now, I'm not saying this is actually a good approach; it's probably going to be slow and the right way to do this, if performance matters, may be to sort the whole collection by these different criteria and then look at the different parts of the sorted collection.
But if you want to use GroupBy and IGroupings to manage it, you're working at it from the wrong end. You want to start at the deepest level first and work up.
var groups = rows
.GroupBy(x => new { x.A, x.B, x.C, x.D, x.E, x.F })
.GroupBy(x => new { x.Key.A, x.Key.B, x.Key.C, x.Key.D, x.Key.E })
.GroupBy(x => new { x.Key.A, x.Key.B, x.Key.C, x.Key.D, })
.GroupBy(x => new { x.Key.A, x.Key.B, x.Key.C })
.GroupBy(x => new { x.Key.A, x.Key.B })
.GroupBy(x => x.Key.A);
groups.First().Key; // will be an A value
groups.First().First().First(); // will be an A, B, C group
GroupBy actually supports giving a list of elements to group by. Each group will contain the same first 3 items (A, B & C). You can get the key with the .Key method, and play around with the different rows with foreach. See Example:
var groups = Elements.GroupBy(x => new {x.A, x.B, x.C});
foreach (var group in groups)
{
Trace.WriteLine(group.Key + ": " + group.Count());
foreach (var row in group)
{
Trace.WriteLine(row.D);
}
}
Edit: Ahh, ok - what you need is this then:
var groups = Elements
.GroupBy(a => new {a.A})
.Select(g1 => new {
A = g1.Key,
Groups = g1
.GroupBy(b=> new {b.B})
.Select(g2 => new {
B = g2.Key,
Groups = g2
.GroupBy(c => new {c.C})
.Select(g3 => new {
C = g3.Key,
Rows = g3
})
})
});
foreach (var groupA in groups)
{
Trace.WriteLine(groupA.A);
foreach (var groupB in groupA.Groups)
{
Trace.WriteLine("\t" + groupB.B);
foreach (var groupC in groupB.Groups)
{
Trace.WriteLine("\t\t" + groupC.C);
foreach (var row in groupC.Rows)
{
Trace.WriteLine("Row: " + row.ToString());
}
}
}
}

Categories

Resources