473,320 Members | 1,978 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 2500
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.