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 |

Saber ShaikhPosted Dec 15, 2014, 11:37 PM
Send Me Select query in SQL
I will make in LINQ
My Blog : http://aspnettutorialscode.blogspot.in/
Thank You
Rahul SinghPosted Dec 15, 2014, 12:14 PM
Saber ShaikhPosted Dec 15, 2014, 7:23 AM
Try This
var Result = from p in db.tbl_name
group p by p.CategoryID into g
select new {
CategoryID= g.Key,
Fruits
};
Lawrence PondPosted Nov 26, 2014, 1:08 AM
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
VulpesPosted Oct 30, 2014, 8:38 PM
Rahul SinghPosted Oct 29, 2014, 12:28 PM
VulpesPosted Oct 29, 2014, 7:55 AM
>();
The output is: