473,513 Members | 2,563 Online
Bytes | Software Development & Data Engineering Community
+ 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 2511
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
549
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
1005
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
964
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
2214
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
1192
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
220
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
1016
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
921
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
819
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
1174
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...
0
7259
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
7158
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7380
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
7535
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5683
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4745
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
1592
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
455
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.