Linq Gruping Dynamically
-
Friday, April 20, 2012 5:48 AM
Hi i want to write dynamic Grouping for my code.
var categories =
from p in kk //KK List.
group p by new
{
Sec = "GroupColumnName.LastOrDefault().ToString()" //Dyanamic Coluname
} into g
select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.PO_NetAmount //Dynamic Columnname) };how can I achieve this.
Amitsp
All Replies
-
Friday, April 20, 2012 6:41 PMModerator
See my blog article entitled C#: Finding List Duplicates Using the GroupBy Linq Extension and Other GroupBy Operations and Usage Explained for I believe you want to group by with one Key or a Non Related Key (See that section) where I provide this example
List<string> theList = new List<string>() { "Alpha", "Alpha", "Beta", "Gamma", "Delta" }; theList.GroupBy(txt => 1 ) .ToList() .ForEach(groupItem => Console.WriteLine("The Key ({0}) found a total of {1} times with a total letter count of {2} characters", groupItem.Key, groupItem.Count(), groupItem.Sum(it => it.Count()))); // Output: // The Key (1) found a total of 5 times with a total letter count of 24 characters
William Wegerson (www.OmegaCoder.Com)
- Marked As Answer by OmegaManMVP, Moderator Tuesday, May 15, 2012 5:17 PM

