I have an input list test
class Tracker
{
public string Toolid {get;set;}
public string Description {get;set;}
public int length {get;set;}
public int breadth {get;set;}
public int height {get;set;}
}
List<Tracker> test = new List<Tracker>();
test.Add( new Tracker {Toolid="A.1",Description ="ABC",length = 10, breadth =10,height = 50});
test.Add( new Tracker {Toolid="A.1",Description ="ABC", length = 10, breadth =10,height = 50});
test.Add( new Tracker {Toolid="C.1",Description ="ABCD", length = 10, breadth =10,height = 50});
test.Add( new Tracker {Toolid="D.1",Description ="Admin123", length = 10, breadth =10,height = 50});
This list contain more values like weight, colour etc.
For better understanding I have added only 5 member variables in the class Tracker.
I need to Group the list test based on the values of another list (grpList).
This list (grpList ) is dynamic, hence the number of parameter and values in the list may change.
So I need a dynamic Group By of list using LINQ query.
case 1 : sometimes this list grpList contain 2 values .
List <string> grpList = new List<string>();
grpList.Add(ToolId);
grpList.Add(Description);
if So , I have to group the list test with ToolId and Description,
case 2 : if list grpList contain N values , I have to group the list test with 'N' values .
The number of values in the grpList varies. I have group the main list test using the values in grpList. If grpList contain 2 values ,group the test list with 2 values . if If grpList contain 5 values , group the test list with 5 values.
NB : I need to Group the list test ( Main list).
grpList values only for grouping .
try reflection:
List<string> grpList = new List<string>();
grpList.Add("Toolid");
grpList.Add("Description");
var groups = new Dictionary<string, IEnumerable>();
var all_properties = typeof(Tracker).GetProperties();
foreach ( var prop_name in grpList )
{
var prop = all_properties.First( x => x.Name == prop_name);
var group = test.GroupBy( x => prop.GetValue( x ) );
groups.Add( prop_name, group );
}
if you want to have an sql-like nested grouping, apply the GroupBy to the resulting groups:
var groups = new List<List<Tracker>>() { test };
foreach ( var prop_name in grpList )
{
var prop = all_properties.First( x => x.Name == prop_name);
var newgroups = new List<List<Tracker>>();
foreach ( var group in groups)
{
var subgroups = group.GroupBy( x => prop.GetValue( x ) );
newgroups.AddRange( subgroups.Select(g => g.ToList()).ToList() );
}
groups = newgroups;
}
I used Enumerable.GroupBy Method selector predicate.
Here's how I generated the predicate and the solution seems to work.
public class Tracker
{
public string Toolid { get; set; }
public string Description { get; set; }
public int length { get; set; }
public int breadth { get; set; }
public int height { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Tracker> test = new List<Tracker>();
test.Add(new Tracker { Toolid = "A.1", Description = "ABC", length = 50, breadth = 10, height = 50 });
test.Add(new Tracker { Toolid = "A.1", Description = "ABC", length = 20, breadth = 10, height = 50 });
test.Add(new Tracker { Toolid = "C.1", Description = "LMN", length = 10, breadth = 10, height = 50 });
test.Add(new Tracker { Toolid = "D.1", Description = "Admin123", length = 7, breadth = 10, height = 50 });
List<string> grpList = new List<string>();
grpList.Add("length");
grpList.Add("Description");
var sourceParm = Expression.Parameter(typeof(Tracker), "x");
List<Expression> propertyExpressions = new List<Expression>();
foreach (var f in grpList.ToArray())
{
Expression conv = Expression.Convert(Expression.Property(sourceParm, f), typeof(object));
propertyExpressions.Add(conv);
}
var concatMethod = typeof(string).GetMethod(
"Concat",
new[] { typeof(object), typeof(object), typeof(object) });
Expression body = propertyExpressions.Aggregate((x, y) => Expression.Call(concatMethod,
x,
Expression.Constant(","),
y));
var groupSelector = Expression.Lambda<Func<Tracker, string>>(body, sourceParm);
var j = test.GroupBy(groupSelector.Compile());
}
I am making a group by linq statement where i convert a single list of data into an list with a nested list. Here is my code so far:
[TestMethod]
public void LinqTestNestedSelect2()
{
// initialization
List<combi> listToLinq = new List<combi>() {
new combi{ id = 1, desc = "a", name = "A", count = 1 },
new combi{ id = 1, desc = "b", name = "A", count = 2 },
new combi{ id = 2, desc = "c", name = "B", count = 3 },
new combi{id = 2, desc = "d", name = "B", count = 4 },
};
// linq group by
var result = (from row in listToLinq
group new { des = row.desc, count = row.count } by new { name = row.name, id = row.id } into obj
select new A { name = obj.Key.name, id = obj.Key.id, descriptions = (from r in obj select new B() { des = r.des, count = r.count }).ToList() }).ToList();
// validation of the results
Assert.AreEqual(2, result.Count);
Assert.AreEqual(2, result[0].descriptions.Count);
Assert.AreEqual(2, result[0].descriptions.Count);
Assert.AreEqual(2, result[1].descriptions.Count);
Assert.AreEqual(2, result[1].descriptions.Count);
}
public class A
{
public int id;
public string name;
public List<B> descriptions;
}
public class B
{
public int count;
public string des;
}
public class combi
{
public int id;
public string name;
public int count;
public string desc;
}
This is fine if the objects are small like the example. However I will implement this for objects with a lot more properties. How can I efficiently write this statement so I don't have to write field names twice in my linq statement?
I would like to return the objects in the statement and I want something like:
// not working wishfull thinking code
var result = (from row in listToLinq
group new { des = row.desc, count = row.count } by new { name = row.name, id = row.id } into obj
select new (A){ this = obj.key , descriptions = obj.ToList<B>()}).ToList();
Background: I am re writing a web api that retrieves objects with nested objects in a single database call for the sake of db performance. It's basically a big query with a join that retrieves a crap load of data which I need to sort out into objects.
probably important: the ID is unique.
EDIT:
based on the answers so far I have made a solution which sort of works for me, but is still a bit ugly, and I would want it to be better looking.
{
// start part
return (from row in reader.AsEnumerable()
group row by row.id into grouping
select CreateA(grouping)).ToList();
}
private static A CreateA(IGrouping<object, listToLinq> grouping)
{
A retVal = StaticCreateAFunction(grouping.First());
retVal.descriptions = grouping.Select(item => StaticCreateBFunction(item)).ToList();
return ret;
}
I hope the StaticCreateAFunction is obvious enough for what it does. In this scenario I only have to write out each property once, which is what I really wanted. But I hope there is a more clever or linq-ish way to write this.
var result = (from row in listToLinq
group new B { des = row.desc, count = row.count } by new A { name = row.name, id = row.id } into obj
select new A { name = obj.Key.name, id = obj.Key.id, descriptions = obj.ToList() }).ToList();
You can add to each of the A and B classes a constructor that receives a combi and then it takes from it only what it needs. For example for a:
public class A
{
public A(combi c)
{
id = c.id;
name = c.name;
}
}
public class B
{
public B(combi c)
{
count = c.count;
des = c.desc;
}
}
Then your query can look like:
var result = (from row in listToLinq
group row by new { row.id, row.name } into grouping
select new A(grouping.First())
{
descriptions = grouping.Select(item => new B(item)).ToList()
}).ToList();
If you don't like the grouping.First() you can then override Equals and GetHashCode and then in the group by do by a new a with the relevant fields (which will be those in the Equals) and then add a copy constructor from a
Another way, in which you decouple the A/B classes from the combi is to extract the convert logic to a collection of static methods.
I have searched through many topics, find some relevant answers too, but I am still not able to reach to a solution, hence I am posting this question.
Problem Description
EmployeeResponse1 = [{"Ques":"1","Rating":"7"},{"Ques":"2","Rating":"1"},{"Ques":"3","Rating":"6"},{"Ques":"4","Rating":"1"},{"Ques":"5","Rating":"1"},{"Ques":"6","Rating":"1"},{"Ques":"7","Rating":"7"},{"Ques":"8","Rating":"1"},{"Ques":"9","Rating":"1"},{"Ques":"10","Rating":"1"},{"Ques":"11","Rating":"1"},{"Ques":"12","Rating":"1"},{"Ques":"13","Rating":"1"},{"Ques":"14","Rating":"1"},{"Ques":"15","Rating":"1"},{"Ques":"16","Rating":"10"}]
EmployeeResponse2 = [{"Ques":"1","Rating":"5"},{"Ques":"2","Rating":"4"},{"Ques":"3","Rating":"7"},{"Ques":"4","Rating":"8"},{"Ques":"5","Rating":"5"},{"Ques":"6","Rating":"9"},{"Ques":"7","Rating":"10"},{"Ques":"8","Rating":"4"},{"Ques":"9","Rating":"9"},{"Ques":"10","Rating":"6"},{"Ques":"11","Rating":"6"},{"Ques":"12","Rating":"6"},{"Ques":"13","Rating":"7"},{"Ques":"14","Rating":"7"},{"Ques":"15","Rating":"9"},{"Ques":"16","Rating":"8"}]
I have these two JSON strings in c# (there can be more).. Now I want to make a final JSON string which will be like:
EmployeeResponseAvg = [{"Ques":"1","Rating":"6"},{"Ques":"2","Rating":"2.5"},{"Ques":"3","Rating":"6.5"},{"Ques":"4","Rating":"4.5"},{"Ques":"5","Rating":"3"},{"Ques":"6","Rating":"5"},{"Ques":"7","Rating":"8.5"},{"Ques":"8","Rating":"2.5"},....,{"Ques":"16", "Rating": "9"}]
like I want rating of Ques = 1 should be the average of Rating (Ques = 1 of string 1) and Rating (Ques = 1 of string 2)... similarly for other questions
i.e like FINAL =[{ QUES = 1, RATING = (Emp1(Rating.WHERE(QUES = 1), Emp2(Rating.WHERE(QUES = 1),).AVERAGE),....................}]
Work So Far
MODEL -> SurveyResponse.cs
public class SurveyResponse
{
public string Ques { get; set; }
public string Rating { get; set; }
}
public class ResponseDataCalls
{
public static SurveyResponse PutData(string t, string v)
{
SurveyResponse s = new SurveyResponse();
s.Ques = t;
s.Rating = v;
return s;
}
}
WebAPI RevGroupChartController.cs
public class RevGroupChartController : ApiController
{
private hr_toolEntities _db = new hr_toolEntities();
public object Get(int cid, int gid)
{
spiderChart obj = new spiderChart();
var group_employees = (from ge in _db.hrt_group_employee
where ge.fk_group_id == gid
select ge.fk_employee_id).ToList();
List<string> EMP = new List<string>();
List<string> SUP = new List<string>();
List<SurveyResponse> EmpResponse = new List<SurveyResponse>();
List<SurveyResponse> SupResponse = new List<SurveyResponse>();
List<List<SurveyResponse>> tmpEMP = new List<List<SurveyResponse>>();
List<List<SurveyResponse>> tmpSUP = new List<List<SurveyResponse>>();
foreach(var emp in group_employees)
{
int eid = Convert.ToInt32(emp);
var Data = (from d in _db.hrt_cycle_response
join g in _db.hrt_cycle_groups on d.hrt_cycle.pk_cycle_id equals g.fk_cycle_id
where d.fk_cycle_id == cid && g.fk_group_id == gid && d.fk_employee_id == eid
select new
{
d.response_employee_answers,
d.response_supervisor_answers
}).First();
EMP.Add(Data.response_employee_answers);
SUP.Add(Data.response_supervisor_answers);
}
foreach(var e in EMP)
{
//tmpEMP = new JavaScriptSerializer().Deserialize<TEMP>(e);
var s = new JavaScriptSerializer();
List<SurveyResponse> em = s.Deserialize<List<SurveyResponse>>(e);
tmpEMP.Add(em);
}
foreach (var s in SUP)
{
//tmpSUP = new JavaScriptSerializer().Deserialize<TEMP>(s);
var e = new JavaScriptSerializer();
List<SurveyResponse> sp = e.Deserialize<List<SurveyResponse>>(s);
tmpSUP.Add(sp);
}
var empl = _db.hrt_questions.Select(x => new { x.question_name }).ToList();
List<int[]> Emprating = new List<int[]>();
//int avgRating;
int cnt = 0;
foreach(var item in tmpSUP)
{
int noofQ = item.Count;
int[] i = new int[noofQ];
for (int y = 0; y > tmpSUP.Count; y++)
{
i[y] = Convert.ToInt32(item[cnt].Rating);
}
Emprating.Add(i);
cnt++;
}
//obj.Employee = Data.response_employee_answers;
//obj.Supervisor = Data.response_supervisor_answers;
obj.ques = new List<object>();
for (int i = 0; i < empl.Count; i++)
{
obj.ques.Add(empl[i].question_name);
}
return obj;
}
public class TEMP
{
public List<SurveyResponse> data { get; set; }
}
}
Explanation of Code
I pass a cycle ID and a group ID...
Each group has more than 1 employee and each employee has a supervisor
so if say group ID 1023 has 2 employees.
Now we have 2 employees and 2 supervisors
we have a json record for each of them
LIKE DB TABLE RESPONSE {fk_emp_id, fk_sup_id, cycle_id, emp_reponse(json), supervisor_response(json)}
so I need to make ONE JSON string for employees (which contains the average of all ratings)
and ONE JSON string for SUPERVISOR (again, average of both the JSONs)
there could be any number of employees, depending on the group size
and each employee will always have a supervisor
In short I want a a string like:
FinalEmployeeResponse = [{'Ques': '1', 'Rating': 'R1'}, {'Ques': '2', 'Rating': 'R2'}, {'Ques': '3', 'Rating': 'R3'}, {'Ques': '4', 'Rating': 'R4'}, ........, {'Ques': '16', 'Rating': 'R16'}]
Here, R1 = AVERAGE(Emp1json.Rating.WHERE('Ques' = 1), Emp2json.Rating.WHERE('Ques' = 1), .....)
and
R2 = AVERAGE(Emp1json.Rating.WHERE('Ques' = 2), Emp2json.Rating.WHERE('Ques' = 2), .....)
... and so on....
Looking forward to your responses.
I am new on stack overflow, please ask for more details if I have missed something.
The correct way to do this is to parse this as JSON. The quick and dirty way is:
static void Main(string[] args)
{
string json1 = #"[{""Ques"":""1"",""Rating"":""7""},{""Ques"":""2"",""Rating"":""1""},{""Ques"":""3"",""Rating"":""6""},{""Ques"":""4"",""Rating"":""1""},{""Ques"":""5"",""Rating"":""1""},{""Ques"":""6"",""Rating"":""1""},{""Ques"":""7"",""Rating"":""7""},{""Ques"":""8"",""Rating"":""1""},{""Ques"":""9"",""Rating"":""1""},{""Ques"":""10"",""Rating"":""1""},{""Ques"":""11"",""Rating"":""1""},{""Ques"":""12"",""Rating"":""1""},{""Ques"":""13"",""Rating"":""1""},{""Ques"":""14"",""Rating"":""1""},{""Ques"":""15"",""Rating"":""1""},{""Ques"":""16"",""Rating"":""10""}]";
string json2 = #"[{""Ques"":""1"",""Rating"":""5""},{""Ques"":""2"",""Rating"":""4""},{""Ques"":""3"",""Rating"":""7""},{""Ques"":""4"",""Rating"":""8""},{""Ques"":""5"",""Rating"":""5""},{""Ques"":""6"",""Rating"":""9""},{""Ques"":""7"",""Rating"":""10""},{""Ques"":""8"",""Rating"":""4""},{""Ques"":""9"",""Rating"":""9""},{""Ques"":""10"",""Rating"":""6""},{""Ques"":""11"",""Rating"":""6""},{""Ques"":""12"",""Rating"":""6""},{""Ques"":""13"",""Rating"":""7""},{""Ques"":""14"",""Rating"":""7""},{""Ques"":""15"",""Rating"":""9""},{""Ques"":""16"",""Rating"":""8""}]";
string averages = AverageNodes(json1, json2);
Console.WriteLine(averages);
Console.ReadKey();
}
private static string AverageNodes(params string[] json)
{
var regex = new Regex(#"(""Ques"":""(?<question>\d+)"",""Rating"":""(?<rating>\d+)"")", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
var ANUs = regex.Matches(string.Join("", json))
.Cast<Match>()
.Select(m => new { Question = m.Groups["question"].Value, Rating = int.Parse(m.Groups["rating"].Value) })
.GroupBy(a => a.Question, a => a.Rating)
.Select(a => string.Format("{{\"Ques\":\"{0}\",\"Rating\":\"{1}\"}}", a.Key, a.Average()));
return "[" + string.Join(",", ANUs) + "]";
}
I found a 1 line answer to this using LINQ.
double _avg1 = tmpEMP.Select(x => Convert.ToInt32(x.ElementAt(i).Rating)).Average();
I have a list of codes as follows
public Code{
int id;
string Description;
}
List<Code> AllCodes;
I have a list of selected codes from a different source.
var relatedCodes = //gets the list of int 'id's from a different source.
Using linq, I need to join AllCodes and relatedCodes so that the resultant list contains all the Code elements of the given ids. It is known that all the int values in relatedCodes are valid ids in AllCodes. [relatedCodes is an int array]
result = //how to write the linq expression?
I was trying something like this but it throws error
result = AllCodes.All(x => x.Code==relatedCodes);
First of all there is nothing to do with Join. Question is briefly How can I get the Codes of which relatedCodes contains the id?. You can use Where to filter your list.
var result = AllCodes.Where( c=> relatedCodes.Contains(c.id));
List<Code> result = AllCodes.Where(x => relatedCodes.Contains(x.id)).ToList();
EDIT:
Since relatedCodes is of type int[] (I used an array of type Code) the solution looks slightly different, but not by too much:
var relatedCodes = new int[2] { 2, 4 };
var joinedCodes = from ac in AllCodes
join rc in relatedCodes on ac.Id equals rc
select ac;
ORIGINAL answer
One possibility is to use join:
void Main()
{
var AllCodes = new List<Code>()
{
new Code() {Id = 1, Description="Foo1"},
new Code() {Id = 2, Description="Bar2"},
new Code() {Id = 3, Description="Foo3"},
new Code() {Id = 4, Description="Bar4"}
};
var relatedCodes = new Code[2]
{
new Code() {Id = 2, Description="Bar2"},
new Code() {Id = 4, Description="Bar4"}
};
var joinedCodes = from ac in AllCodes
join rc in relatedCodes on ac.Id equals rc.Id
select ac;
joinedCodes.Dump();
}
// Define other methods and classes here
public class Code{
public int Id { get; set; }
public string Description { get; set; }
}
Ouput:
I have many Object1A, say IEnumerable<Object1A>.
public class Object1A {
public string text;
public datetime date;
public decimal percent;
public Object3 obj;
}
Many of these objects have the same text, date, and percent, but have a different obj. I want to transform the list such that the output will be a IEnumerable<Object1B> where
public class Object1B{
public string text;
public datetime date;
public decimal percent;
public IEnumerable<Object3> objs;
}
My current apporach is a bit clunky, and listed below
IEnumerable<Object1A> a = GetSomeConstruct();
var lookup = a.ToLookup( t => t.text);
var b = new List<Object1b>();
foreach(var group in lookup){
var itemA = group.first();
var itemB = new Object1b(){
text = itemA.text,
date = itemA.date,
percent = itemA.percent
};
itemB.objs = pair.Select(t => t.obj);
b.Add(itemB);
}
Can this approach be refined? It doesn't seem to run to slow, but it seems like it could be better. I'm looking for a more terse approach if possible.
edit: yeah, this was a dumb question, cudos to the downvote....
simple answer
var b_objects = a_objects.GroupBy(t => new {t.Text})
.Select( t => new Object1B
{ Text = t.Key.Text,
Percent = t.First().Percent,
Date = t.First().Date,
Objs = t.Select( o => o.Obj).ToList()
});
Guess you want something like this?
var b = from a in GetSomeConstruct()
group a.obj by new { a.text, a.date, a.percent } into grp
select new Object1B
{
text = grp.Key.text,
date = grp.Key.date,
percent = grp.Key.percent,
objs = grp
};
You can use anonymous types with join and group by. Their GetHashCode and Equals overloads operate on each member.