473,468 Members | 1,323 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

LINQ 101 question

In this LINQ example, how do you get at the values within the groupings?

string[] anagrams = {"from", "salt", "earn ", "last ", "near ", "form
"};

var orderGroups = anagrams.GroupBy(
w =w.Trim(),
new AnagramEqualityComparer());
*** Sent via Developersdex http://www.developersdex.com ***
Aug 20 '08 #1
3 2505
On Aug 20, 4:46*pm, Mike P <mike.p...@gmail.comwrote:
In this LINQ example, how do you get at the values within the groupings?

string[] anagrams = {"from", "salt", "earn ", "last ", "near ", "form
"};

* * * * var orderGroups = anagrams.GroupBy(
* * * * * * * * * * w =w.Trim(),
* * * * * * * * * * new AnagramEqualityComparer());
GroupBy returns an IGrouping (IIRC) which has a Key property and
implements IEnumerable<Tfor the appropriate T - so you typically
just use "foreach" over it.

Here's an example:
using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
static void Main()
{
string[] strings = { "These", "strings", "will",
"be", "grouped", "by", "length", "and", "then",
"displayed", "in", "their", "groups" };

var groups = strings.GroupBy(x =x.Length);

foreach (var group in groups)
{
Console.WriteLine("Words of length: {0}", group.Key);
foreach (var word in group)
{
Console.WriteLine(" {0}", word);
}
}
}
}

Jon
Aug 20 '08 #2
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in news:05bf5f2b-589f-44db-
be***************@m45g2000hsb.googlegroups.com:
On Aug 20, 4:46*pm, Mike P <mike.p...@gmail.comwrote:
>In this LINQ example, how do you get at the values within the
groupings?
>>
string[] anagrams = {"from", "salt", "earn ", "last ", "near ", "form
"};

* * * * var orderGroups = anagrams.GroupBy(
* * * * * * * * * * w =w.Trim(),
* * * * * * * * * * new AnagramEqualityComparer());

GroupBy returns an IGrouping (IIRC) which has a Key property and
implements IEnumerable<Tfor the appropriate T - so you typically
just use "foreach" over it.

Here's an example:
using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
static void Main()
{
string[] strings = { "These", "strings", "will",
"be", "grouped", "by", "length", "and", "then",
"displayed", "in", "their", "groups" };

var groups = strings.GroupBy(x =x.Length);

foreach (var group in groups)
{
Console.WriteLine("Words of length: {0}", group.Key);
foreach (var word in group)
{
Console.WriteLine(" {0}", word);
}
}
}
}

Jon
What if I only want the first item and do not want to do a foreach?

I want to do something like this:

string myString = strings[0];

But that is not an option.

--
Only the Best Freeware
http://www.vbmark.com
Aug 21 '08 #3
On Thu, 21 Aug 2008 12:45:38 -0700, vbMark <no@email.comwrote:
What if I only want the first item and do not want to do a foreach?

I want to do something like this:

string myString = strings[0];

But that is not an option.
Try the System.Linq.Enumerable.First() method. For example, if you want
the group of the shortest words:

Console.WriteLine("The shortest words have {0} characters. They
are:", groups.First().Key);
foreach (var word in groups.First())
{
Console.WriteLine(" {0}", word);
}

Pre-LINQ, you could of course always just put a "break" at the bottom of
your "foreach()" loop to ensure that you only ever process the first
element. But LINQ makes it nicer. :)

Pete
Aug 21 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: BeSharp | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some increasing LINQ evangelism down here in Germany.). ...
0
by: Griff | last post by:
Hi Is it possible to query a structured file that is a FIXED WIDTH file rather than a delimited file? I think it would be great to first define how many columns one is expecting and the width...
0
by: CSharper | last post by:
This may be a dump question, so please bear with me. I have an xml file like the following <teacher> <name>jkjk</name> <phone>122</phone> </teacher> <student> .... </student>
1
by: 0to60 | last post by:
Let's say we have your basic Invoices and InvoiceItems table. If we load this in with LINQ: var query = from i in db.Invoices select i; When I then loop through my invoices, if I wanna...
10
by: damiensawyer | last post by:
Hi, I have the following code extract... ---top--- List<PersonPersons = new List<Person>(); Persons.Add(new Person("Peter", 28,"Perth")); Persons.Add(new Person("Matthew", 31,...
4
by: CSharper | last post by:
I would like know, will it be possible to run a linq statement generated on the fly by a program? Lets say, I have string like the following string t = "from c in doc.Decentents('Value') select...
1
by: Scott M. | last post by:
How would I use LINQ to XML to extract just the text (not the markup) of the following: <description><!]></description> In other words, I'm only interested in: In an interview, David Hajdu,...
2
by: kfparri | last post by:
Hi, I am trying to join together a table out of a database using Linq to SQL with a list of class objects using a linq statement. I don't know if this is possible, so could someone please help...
0
by: Tony Johansson | last post by:
Hello ! Have you any simple example where you use LINQ to join a DataSet and a xml file. //Tony
1
by: Leon Mayne | last post by:
I'm new to LINQ, and so having a small problem trying to left outer join two generic lists of business objects. I have a collection of department objects which I want to left join to a...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.