Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query Group By and Selecting First Items

Tags:

c#

.net

linq

I have a String array kinda like this:

// icon, category, tool String[,] subButtonData = new String[,] {     {"graphics/gui/brushsizeplus_icon", "Draw", "DrawBrushPlus"},     {"graphics/gui/brushsizeminus_icon", "Draw", "DrawBrushMinus"},     {"graphics/gui/freedraw_icon", "Draw", "DrawFree"},     {"graphics/gui/linedraw_icon", "Draw", "DrawLine"},     {"graphics/gui/rectangledraw_icon", "Draw", "DrawRectangle"},     {"graphics/gui/ellipsedraw_icon", "Draw", "DrawEllipse"},     {"graphics/gui/brushsizeplus_icon", "Brusher", "BrusherBrushPlus"},     {"graphics/gui/brushsizeminus_icon", "Brusher", "BrusherBrushMinus"},     {"graphics/gui/brushsizeplus_icon", "Text", "TextBrushPlus"},     {"graphics/gui/brushsizeminus_icon", "Text", "TextBrushMinus"}, }; 

Then I populate a List<Button> with my Button Type named mainButtons

This is how I query for grouping for Category:

var categories = from b in mainButtons                  group b by b.category into g                  select new { Category = g.Key, Buttons = g }; 

How can I select the first item of each group in my main List? (without iterating each and adding to another List?)

like image 227
JML Avatar asked Aug 05 '11 23:08

JML


People also ask

How do you Select the top 1 record in LINQ?

Use the OrderByDesecnding() amd First() query operators. No - LINQ to SQL does the optimization of doing everything on the server side and getting you only one record. Great! That works, it produces a nice "select top 1" T-SQL.

How do you Select records with Max ID that GroupBy multiple columns in LINQ to SQL?

In SQL, it is very simple to do: SELECT * FROM [dbo]. [tblOrderDeliveryGroup] t1 WHERE [DeliveryGroupId] IN ( SELECT MAX([DeliveryGroupId]) FROM [dbo]. [tblOrderDeliveryGroup] t2 WHERE (t1.

Which function is used to get first record in LINQ collection?

Accepted Answer. data . GroupBy( x => x.

What is use of first () in LINQ?

C# Linq First() Method Use the First() method to get the first element from an array. Firstly, set an array. int[] arr = {20, 40, 60, 80 , 100}; Now, use the Queryable First() method to return the first element.


1 Answers

var result = list.GroupBy(x => x.Category).Select(x => x.First()) 
like image 96
Oscar Fraxedas Avatar answered Sep 29 '22 07:09

Oscar Fraxedas