I made a simple dynamic object:
class Row
{
Dictionary<string, object> properties = new Dictionary<string, object>();
private int rIndex;
public Row(int rIndex)
{
this.rIndex = rIndex;
}
public object this[string name]
{
get
{
if (properties.ContainsKey(name))
{
return properties[name];
}
return null;
}
set
{
properties[name] = value;
}
}
public int RIndex
{
get { return rIndex; }
set { rIndex = value; }
}
}
I get the coloumn that i use to group from a configuration file.
Group by different value for example like this :
var t = lst.GroupBy(x => new { x1 = x["job"], x2 = x["schema"], x3 = x["line"], x4 = x["plant"], x5 = x["mod"], x6 = x["tag"] }).Select(g => new { g.Key.x1, g.Key.x2, g.Key.x3, g.Key.x4, g.Key.x5, g.Key.x6, });
this works well but i think it's too static.
How can i implement a dynamic Group by clause? Is it possible, inside the Group By clause, get the Dictionary key value that is inside the dynamic object?
Thanks all in advance.
Okay, I think it probably makes sense to have something like a RowView
class, which contains a reference to a Row
, and the properties you're interested in (a subset of the row's properties). You can then make it implement IEquatable<RowView>
, such that two RowView
objects are equal if and only if:
For convenience, I'd probably add a CreateView(IEnumerable<string> properties)
method to Row
, so you can call:
var t = lst.GroupBy(x => x.CreateView(groupingProperties));
(I'd also advise using an automatically-implemented property for RIndex
to simplify the code - and ideally rename it, as it's not clear what it's for at the moment.)
See more on this question at Stackoverflow