views:

43

answers:

1

I have a table where a record looks like this

varchar(255) Name  
varchar(255) Text  
varchar(255) Value 

Name is the DDL name, Text is what is displayed, and Value is returned upon selection. There are between one and twenty options for each Name. Without iterating though each option like a cursor, is there any way to pull out a list of objects, one for each unique DDL Name, using Linq and C#?

A sample of the data:

Beds   '4 (10)'  4
Beds   '5 (1)'   5
Beds   '7 (1)'   7
Baths  'NA (13)' NULL
Baths  '0 (1)'   0
Baths  '1 (13)'  1

I was thinking about doing an outer select to get the unique Names, then an inner select to get the list of options for it, then return the set as a List of a set of Lists.

+5  A: 

Sure, just use group ... by

var query = from item in context.TableName
            group item by item.Name;

Alternatively without a query expression:

var query = context.TableName.GroupBy(item => item.Name);

The result will be an IQueryable<IGrouping<string, ItemType>>. Each element in the result will be a grouping: a key and a sequence of items with that key.

Jon Skeet
I liked the answer so much I pre-ordered your new book. LOL. I figure it is full of the same valuable advice.
Dr. Zim
I used foreach( var a in context.TableName.GroupBy(item => item.Name)) { foreach (var b in a) { //a is now a TableName row}}
Dr. Zim