Flatten a Collection with LINQ ?

I'm trying to get a "flat list" of values.

Below is the sample.

Desired Results:

Bobbie Brady has these toys : TeddyBear,Wagon,TonkaTruck
Cindy Brady has these toys : Dollie,TeaSet,Insta-Bake

Some kind of delimiter between the toys would be nice (comma above).

All code below, I'm just missing the magically LINQ statement.

THANKS!




public class Kid

{

public Kid(string firstName, string lastName)

{

this.FirstName = firstName;

this.LastName = lastName;

this.FavoriteToys = new ToyCollection();

}

public string FirstName { get; set; }

public string LastName { get; set; }

public ToyCollection FavoriteToys { get; set; }

}

public class Toy

{

public Toy(string name) { this.ToyName = name; }

public string ToyName { get; set; }

}

public class KidCollection : List<Kid>{}

public class ToyCollection : List<Toy>{}



static void Main(string[] args)

{



KidCollection kc = new KidCollection();

kc.Add(new Kid("Bobbie", "Brady"));

kc.Add(new Kid("Cindy", "Brady"));

kc.Add(new Kid("Danny", "Partridge"));

kc[0].FavoriteToys.Add(new Toy("TeddyBear"));

kc[0].FavoriteToys.Add(new Toy("Wagon"));

kc[0].FavoriteToys.Add(new Toy("TonkaTruck"));

kc[1].FavoriteToys.Add(new Toy("Dollie"));

kc[1].FavoriteToys.Add(new Toy("TeaSet"));

kc[1].FavoriteToys.Add(new Toy("Insta-Bake"));

kc[2].FavoriteToys.Add(new Toy("Drums"));

kc[2].FavoriteToys.Add(new Toy("DrumLessons"));

kc[2].FavoriteToys.Add(new Toy("MoreDrumLessons"));



var v = from k in kc

where k.LastName.Contains("Brady")

orderby k.FirstName descending

select k.FirstName + " " + k.LastName + " has these toys : " + 
k.FavoriteToys.SelectMany(l => l.ToyName).ToList();



foreach (string s in v)

Console.WriteLine(s);





}


0
sloan
11/13/2009 2:10:01 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

5 Replies
1745 Views

Similar Articles

[PageSpeed] 51

sloan wrote:
> I'm trying to get a "flat list" of values.
> 
> Below is the sample.
> 
> Desired Results:
> 
> Bobbie Brady has these toys : TeddyBear,Wagon,TonkaTruck
> Cindy Brady has these toys : Dollie,TeaSet,Insta-Bake
> 
> Some kind of delimiter between the toys would be nice (comma above).

             var v = from k in kc

                     where k.LastName.Contains("Brady")

                     orderby k.FirstName

                     select k.FirstName + " " + k.LastName + " has these 
toys : " +
                     k.FavoriteToys.Select(l => l.ToyName).Aggregate(new 
StringBuilder(), (sb, s) => sb.Append(s + ", "), sb => { 
sb.Remove(sb.Length - 2, 2); return sb.ToString(); });


does that but is a bit ugly in my view (in particular that bit stripping 
the last ", ").




-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
Martin
11/13/2009 3:38:40 PM
Thanks Martin.

When googling (errr:: binging)....I kept finding "Use SelectMany" comments.
I'll have to do some research into Aggregate.

My linq skills are subpar right now.  :<




"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:en%23GkdHZKHA.5108@TK2MSFTNGP06.phx.gbl...
> sloan wrote:
>> I'm trying to get a "flat list" of values.
>>
>> Below is the sample.
>>
>> Desired Results:
>>
>> Bobbie Brady has these toys : TeddyBear,Wagon,TonkaTruck
>> Cindy Brady has these toys : Dollie,TeaSet,Insta-Bake
>>
>> Some kind of delimiter between the toys would be nice (comma above).
>
>             var v = from k in kc
>
>                     where k.LastName.Contains("Brady")
>
>                     orderby k.FirstName
>
>                     select k.FirstName + " " + k.LastName + " has these 
> toys : " +
>                     k.FavoriteToys.Select(l => l.ToyName).Aggregate(new 
> StringBuilder(), (sb, s) => sb.Append(s + ", "), sb => { 
> sb.Remove(sb.Length - 2, 2); return sb.ToString(); });
>
>
> does that but is a bit ugly in my view (in particular that bit stripping 
> the last ", ").
>
>
>
>
> -- 
>
> Martin Honnen --- MVP XML
> http://msmvps.com/blogs/martin_honnen/ 


0
sloan
11/13/2009 5:07:43 PM
sloan wrote:

> When googling (errr:: binging)....I kept finding "Use SelectMany" comments.

SelectMany helps if you have a collection of collections and want to 
flatten that. For instance if you take your KidCollection kc and use
   kc.Select(k => k.FavoriteToys)
then you get a collection of collections (IEnumerable<ToyCollection>). 
If you use
   kc.SelectMany(k = k.FavoriteToys)
instead then you have a flat collection of Toys (IEnumerable<Toy>).
-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
Martin
11/13/2009 5:44:44 PM
sloan schrieb:

> I'm trying to get a "flat list" of values.
> 
> Below is the sample.
> 
> Desired Results:
> 
> Bobbie Brady has these toys : TeddyBear,Wagon,TonkaTruck
> Cindy Brady has these toys : Dollie,TeaSet,Insta-Bake
> 
> Some kind of delimiter between the toys would be nice (comma above).

> All code below, I'm just missing the magically LINQ statement.

> var v = from k in kc 
> where k.LastName.Contains("Brady") 
> orderby k.FirstName descending 
> select k.FirstName + " " + k.LastName + " has these toys : " + 
> k.FavoriteToys.SelectMany(l => l.ToyName).ToList();

Looks like you don't actually need sexy linq-magic here
but a simple string.Join and kind of a subselect
will suffice for a In-Memory query

   var v =  from k in kc
            where k.LastName == "Brady"
            orderby k.FirstName descending
            select k.FirstName + " " + k.LastName
            + " has these toys: " + string.Join (
                "," ,
                (from t in k.FavoriteToys select t.ToyName).ToArray()
            );


SelectMany would be useful if you wouldn't need to keep the
relation between Toy and Owner, but simply wanted a completely
flattened list of all toys of all children, iirc

hth
Christoph

> 
> foreach (string s in v)
> 
> Console.WriteLine(s);
> 
> 
> 
> 
> 
> }
> 
> 
0
Christoph
11/14/2009 1:17:22 PM
Christoph Basedau schrieb:
> sloan schrieb:> 
>> I'm trying to get a "flat list" of values.

>> Desired Results:
>>
>> Bobbie Brady has these toys : TeddyBear,Wagon,TonkaTruck
>> Cindy Brady has these toys : Dollie,TeaSet,Insta-Bake

> Looks like you don't actually need sexy linq-magic here
> but a simple string.Join and kind of a subselect
> will suffice for a In-Memory query
> 
>   var v =  [...]
>            + " has these toys: " + string.Join (
>                "," ,

where

>                (from t in k.FavoriteToys select t.ToyName).ToArray()
>            );
> 

should be condensed to:

  + string.Join(",", k.FavoriteToys.Select(t=>t.ToyName).ToArray());

to look a bit more like black LINQish magic

Christoph

0
Christoph
11/14/2009 1:25:00 PM
Reply:

Similar Artilces:

Access 2007 Email Data Collection
Hi. I am conveting an existing Access 2000 application to 2007 and would like to add the functionality provided by the new Email Data Collection Wizard. My users are used to sending emails from withing the Access application by just pushing button. I would like to provide the wizard's functionality with VBA programming. I'm already familiar with code to open an Outlook session, create email messages and send messages using VBA. I'm assuming there is a way to send the data collection form programatically as well. Can anyone point me to the documentation for this new fu...

Garbage Collection
Hi I would like to know wat does VC++do for garbage collection .I guess Java has a very versatile and strong GC.How about VC++.Wat are the new MFC's availabel with VC The problem with garbage collection is that you have to be able to find all the pointers, and C and C++ don't make this easy. So there is no general-purpose garbage collector possible. Within restricted problem domains, there are GC libraries for C and C++, and if you write a pure managed-code MFC app you get the C# garbage collector free. joe On Tue, 2 Mar 2004 20:21:07 -0800, "CJ" <anonymous@discussi...

Data Collection Via E Mail
Is there any way to edit the field labels on a Data Collection via E mail Form? A2007 collecting data via Outlook. I selected the fields I need whiledesigning the form, and added a brief explanation in each field label - one typo in one field label is set to cost me the re-design of the entire form. I see Resend option, but no option to edit the form. Perhaps if someone knows if and where the form is stored I might be able to edit the fields. Thanks is advance for any help. Tom, As far as I know the email with the HTML-form is made 'on the fly'. Only when you use InfoPath yo...

Collecting the Data entered onto a form into a access table.
I have designed a form in outlook 2003 and want to collect he data in a access table when the form is used to send email. Can any one please help me as I am stuck. I have linked the table to the form but nothing happens when you use the form and send a email. You will need to write code. See http://www.outlookcode.com/d/database.htm for links to samples, etc -- Sue Mosher, Outlook MVP Author of Microsoft Outlook Programming - Jumpstart for Administrators, Power Users, and Developers http://www.outlookcode.com/jumpstart.aspx "Claude Brandon" <claude@umban...

How to collect mailbox information
Hello, I have hundreds mailboxes. I want to know how to collect all mailbox information and download to a file for analysis, e.g. how much storage limit is granted to mailbox. Any idea? Many thanks. ...

Way to get Collections Main to show historical xacts
Is there a way to have the Collections Main window show the historical transactions on a customer? It is a nice window but seems to only show the outstanding items. If this is a credit, can't see how that came to be the case. ...

Collect data from spesific cell in multiple sheets
How can I collect data from cell A1 on sheet 01.01 thru 31.12 (Dates) to summary sheet? I've tried fill and copy formula with different use of ! and $ but I've not been able to solve this by my self. Thank you Hi, The correct syntax is =SUM(Sheet1:Sheet3!A1) Substitute sheet1 & sheet3 for the first/last sheets in the range you want to sum -- Mike When competing hypotheses are otherwise equal, adopt the hypothesis that introduces the fewest assumptions while still sufficiently answering the question. "Espen Rostad" wrote: > How ...

Collections Management Letter functions stop working after installing GP 7.5 SP7
Hello everyone. GP 7.5 SP7 on SQL2000. I just installed SP7 and the Overdue Invoices functions in the Collections Management e-mail screen are longer working. All it prints is either None or 0.00 when the user clicks on Substitute in the E-mail window. In this case, the customer they were trying to e-mail does have overdue invoices. I installed SP7 in both our test and production companies. In the test company, it works just fine. It was a routine upgrade when I was testing it and I did not have to do anything special to make it work. What is causing this to not work all of a sudden? ...

Collect email addresses from a query to
I want to email to a group of people. How can I collect the selected records from a query's [EmailAddress] field, put commas between each address, and drop the result into a microsoft outlook TO field? TIA, Kathy "Kathy Webster" wrote: >I want to email to a group of people. How can I collect the selected >records from a query's [EmailAddress] field, put commas between each >address, and drop the result into a microsoft outlook TO field? > Hi Kathy, Here be some "starting skeleton code" (usually one wants to put the "list" in the BCC...

Collect value
I have 4 cells: H8 I8 J8 K8 If change H8, I8 J8 K8 cells have variable value. I want to change values of H8 from 10 to 150 and collect all 4 cells value in columns AF AG AH AI. Please help me with same VBA code. Thanks. This routine will do the data entry for you and capture the results. To put the code into your workbook, open it and press [Alt]+[F11] to open the VB Editor. Use Insert --> Module in it to open a new code module, then copy and paste the code into it. Select the proper worksheet and then run the Macro. Sub FillAndCapture() Dim homeCell As Range Dim ...

"item not found in this collection"
I try to send mass emails in my VBA codes, but I got the above error message. Can you help me to debug it. Here are the codes. Dim email1 As String email1 = "a@hotmail.com" + ";" + "b@yahoo.com" + ";" + "c@c.com" + ";" + "d@d.com" + ";" + "e@e.com" + ";" + "f@pony.ocn.ne.jp" Dim email2 As String email2 = "g.1@g.com" + ";" + "h.52@h.com" + ";" + "i.34@i.com" Dim strEmail As String Dim strE As String Dim rstE As DAO....

credit manager on the collection main window
Our Credit Manager has asked me to ask if the Credit Manager assigned to the Debtor can be added to the Collection Main window. She finds it very useful for others to see who the customer belongs to. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsof...

How do i make Class Collection in VC++
HI all I Do VB programming and I want to jump in VC++ so i want to create class Collection in VC++ which has Add and remove funciton like in VB will any body help me. thanks Amrit You can use the STL ( Standard Template Library ), it have many container template class as vector, map, set... with functions like Add and Remove "Amrit" wrote: > HI all > I Do VB programming and I want to jump in VC++ > so i want to create class Collection in VC++ which has Add and remove > funciton like in VB > > will any body help me. > > thanks > Amrit > > ...

HELP!Third party solutions for my delivery and cash collection pro
Hi, I need a third party solutions for my problem. I have 6 invoices A, B, C, X, Y Z. I want to be able to choose which invoice will be sent in schedule 1, which invoices will be sent in schedule 2. For example: schedule 1 contains invoice A, B, C. Schedule 2 contains invoice X, Y, Z. When schedule 1 has been delivered, we will receive the delivery report. If there is an invoice which is not delivered, we have the option to re-deliver it or void it. For the invoice that has been delivered, we will be able to post it automatically without opening sales trx entry module again to post th...

Avid Xpress DV Plugins Collection, Lightwave Plugins Collection, updated 28/Aug/2005
Avid Xpress DV Plugins Collection, Lightwave Plugins Collection, updated 28/Aug/2005 buy, risk-free purchase, working, tested, fully functional, very cheap discounted price, low cost, quality OEM software, ============================================================ Avid Xpress DV Plugins Collection, updated 28/Aug/2005 buy, risk-free purchase, working, tested, fully functional, very cheap discounted price, low cost, quality OEM software, Profound Effects Elastic Gasket v2.0 for Avid Xpress Primatte.Keyer.v1.6.for.Avid.Xpress Magic.Bullet.Editor.v.1.01.for.Avid.Xpress.Pro Synthetic.Apert...

Collection Letter Functions
I'm trying to customize some collection letters. I went to the Collections Management Letter Maintenance window and reviewed the documentation, but I cannot figure out how to include the various functions in my collections letters. It appears that I can only modify collection letters in report writer, if thats the case how do I utilize the functions? ...

Add Notes to Credit Memos for Collections Management
Would like ability to Add Notes to Credit Memos for Collections Management. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssolutions/Community/NewsGroups/dgbrowser/en-us/default.mspx?mid=9576abfa-13b7-41b9-b471-f52334ff05db&dg=micro...

Collections Main Fields Question
On the Customer Payment Summary Inquiry (we get there from clicking the "Stats" button on the Collections Main window, there are a few fields that I'm not sure what they mean and how they are calculated. On of them is the Open Order Amount field in Customer Payment Summary Inquiry. How is this amount calculated and from what tables does it gather the information used. The field it corresponds to is RM00103.ONORDAMT. Also, there is another field on the screen that is labeled "Year-to-Date" and has columns for Highest Balance and Avg. Days. What determines the ...

Receiving Multiple Emails but not using pop collection
Ok, here goes... Server 2003 Standard. Exchange 2003 Standard. We use SMTP to send and receive email. 4 of our users have been setup to have their email forwarded to individual external accounts with their own ISPs. However, when these users send emails to each other internally and cc each other (so user 1 sends an email to user 2 and ccs user 3 and 4), there will be 4 copies of the same email within their external accounts. Their internal exchange mailboxes will have only 1 copy, as it should. Why, then, do they get 4 copies in their external email accounts? I read other posts about simila...

Problem with collection classes
Hi, how do I synchronize (to XML using XmlSerializer) something to this: <Alignments name="Road Project"> <Alignment name="Centerline"> <CoordGeom> <Line staStart="0"> <Start>2000 6000</Start> <End>2186.841 6068.005</End> </Line> <Curve rot="cw" /> ... arbitrary number of Line's and Curve's ... in arbitrary order </CoordGeom> ... arbitrary number of CoordGeom's ... </Alignment> .... arbitrary number of Alignment...

Country in Collection letter addresses
The Collection Letter address fields for the Letter Writing Assistant don't include Country. Country is needed for Multi National customer letters. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssolutions/Community/NewsGroups/dgbr...

Using LINQ to SQL with multiple databases
I am working on a new project and hoping to use LINQ to SQL for the data access but have come across the following issue. I need to have my application access 3 databases with similar but not the same table structure, for example Database1 and Database 2 has a table called tblCustomer with 2 columns CustomerKey and CustomerName Database2 has a table called tblCustomer with 3 columns CustomerKey, CustomerName and CustomerPostCode I am looking for a solution that will allow me a query all three databases without the need for 3 GetCustomerList functions as Database1 and Database...

Collecting mails addressed to non-existing users
We have users, whose email domain name ends with, either domain1.com or domain2.com. Users are able to send/receive emails without any problem. I want to create additional one mailbox per domain, which should collect all mails addressed to non-existing user name. For example, if somebody send a mail to user1@domain1.com, and if user1 doesnot exist, this mail should go the "non-existing username mailbox of domain1". Thanks for any help. J Justin On Thu, 9 Sep 2004 11:17:34 +0530, "Justin" <justinkumar@hotmail.com> wrote: >We have users, whose email domain na...

Collections Management
How is the Collections Management module installed in GP10? I am browsing the CD and I am not seeing it in 'Additional Components'. Please help. rcr, Collections Management is now included in the "Select Features" window during the regular GP install. Click on the Collections Management button and select "Install this Feature" or "Install Entire Feature". The Collections Management dictionary will then load during the normal installation. (The Select Features window is available after the "Accept the License agreement" wind...

item not found in this collection
I am trying to modify the criteria parameters in a query "Query1" from a command button in a form, using VBA code. The following code triggers the "item not found in this collection" message. I don't know how to correct it. What am I doing wrong? Private Sub Command79_Click() Dim db As Database Dim qdf As QueryDef Set db = CurrentDb Set qdf = db.QueryDefs("Query1") qdf.Parameters("TagIndex").Value = 1 End Sub Which line gives the error? If its the "Set qdf = ..." line, Query1 doesn't exist (space in nam...