Suppose I have this table:-
Now, i want to group this data either if CategoryIds are same or Fruits are same.
Sample Output:-
Group 1:-
1 Apple
1 Grapes
Group 2:-
2 Tablet
2 Laptop
Group 3:-
5 Coke6 Coke
| CategoryID | Fruits |
| 1 | Apple |
| 1 | Grapes |
| 2 | Tablet |
| 2 | Laptop |
| 5 | Coke |
| 6 | Coke |


VulpesRank #55 · 29.2K reputationPosted Oct 29, 2014, 3:55 AM EDT
>();
The output is:
Rahul SinghRank #1,323 · 1.3K reputationPosted Oct 29, 2014, 8:28 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 30, 2014, 4:38 PM EDT
Lawrence Pond149 reputationPosted Nov 25, 2014, 8:08 PM EST
Hello Friends,
Here is a option that show how to group by either category or fruits Also notice the I change the order of the items on the initial load to show the grouping and results were done correctly Linq is so very powerful I am learning a lot and appreciate the support I receive here on questions, I hope this helps you and others
Notice the code is only a single line two lines to show both methods using dot notation,
void main()
{
var myItemList = new[]
{
new item { category =2, fruit="Tablet"},
new item { category =1, fruit="Apple"},
new item { category=6, fruit="Coke"},
new item { category=2, fruit="Laptop"},
new item { category =5, fruit="Coke"},
new item { category=1, fruit="Grapes"}
};
var myItemsGroupedByCategory = myItemList.GroupBy(p=>new{CATEGORY=p.category}).Select(p=>new{Category=p.Key.CATEGORY, Fruit =p.ToList(), ItemsInGroup =p.Count()}).OrderBy (p =>p.Category );
var myItemsGroupedByFruit = myItemList.GroupBy(p=>new{FRUIT= p.fruit}).Select(p=>new{Fruit =p.Key.FRUIT, Category =p.ToList(), ItemsInGroup =p.Count()}).OrderBy (p =>p.Fruit);
}
public class item
{
public int category { get; set; }
public string fruit { get; set; }
}
RESULTS
ORDER BY CATEGORY
GCAT Cat/Fruit ItemsInGroup
1 2
1 Apple
1 Grapes
2 2
2 Tablet
2 Laptop
5 1
5 Coke
6 1
6 Coke
ORDER BY FRUIT
Fruit Cat/Fruit ItemsInGroup
Apple 1
1 Apple
Coke 2
6 Coke
5 Coke
Grapes 1
1 Grapes
LapTop 1
2 Laptop
Tablet 1
2 Tablet
Saber ShaikhRank #1,687 · 905 reputationPosted Dec 15, 2014, 2:23 AM EST
Try This
var Result = from p in db.tbl_name
group p by p.CategoryID into g
select new {
CategoryID= g.Key,
Fruits
};
Rahul SinghRank #1,323 · 1.3K reputationPosted Dec 15, 2014, 7:14 AM EST
Saber ShaikhRank #1,687 · 905 reputationPosted Dec 15, 2014, 6:37 PM EST
Send Me Select query in SQL
I will make in LINQ
My Blog : http://aspnettutorialscode.blogspot.in/
Thank You