nick zdravcov nick zdravcov - 1 month ago 8x
C# Question

Devide collection linq entity framework

I have a PropertyValues entity which reperesent product properties:

public enum Property { Color = 1, Brand, Size }

public class PropertyValue
public int PropertyValueId { get; set; }
public Property PropertyId { get; set; }
public string Value { get; set; }

public ICollection<Product> Products { get; set; }

public PropertyValue()
Products = new HashSet<Product>();

Cause we have end sequnce of product properties i created an enum Property which keep properties.
I'm trying to achieve following result - to split collection depending on properties. Where the values are an another Dictionary

Dictionary<Property, Dictionary<int, string>> dict = new Dictionary<Property, Dictionary<int, string>>()
new KeyValuePair<Property, Dictionary<int, string>>()
new KeyValuePair<int, string>()
{ 5, "white" }, // ProperyValueId, Value
{ 6, "green"}

I have been looked aside GroupBy and SelectMany, but didn't find a way.
For now i have following:

var query = await db.PropertyValues
.OrderBy(prop => prop.PropertyId)
.Where(prop => prop.PropertyId == Property.Brand)
.ToDictionaryAsync(prop => prop.PropertyValueId, prop => prop.Value);

Dictionary<Property, Dictionary<int, string>> properties = new Dictionary<Property, Dictionary<int, string>>();
properties.Add(Property.Brand, query);

Should return a json. But firstly need to get sequence. Json should look like:

{"colors": [{"5", "Black"}, {"7", "White"}]},
{"brands": [{"78", "Q&Q"}, {"24", "Adidas"}]},

sam sam

The first GroupBy splits the list of PropertyValues by PropertyId, then this grouping is converted to a dictionary that has PropertyId as Key.

The values of each record of our dicionary is composed by creating a new dictionary where the key is PropertyValueId and the value is Value

PropertyValues.GroupBy( k => k.PropertyId )
    .ToDictionary( k => k.First().Value, 
          k => k.ToDictionary( p => p.PropertyValueId, p => p.Value ) );

Now data is structured as you want.