tags:

views:

67

answers:

3

When you query existing linq results, it's like they're stuck a layer deeper than the original result. Let me explain what I mean by this.

In the example below, after getting ResultSorted, to get to the data therein, you have to use RowSorted.All.TableData.Field, but in the unsorted Result, you could just do Row.TableData.Field. In the sorted data, you have to use .All to get to the rest of the data, which is like an extra layer to get to the data you're looking for.

How can I get it so I can query Result without getting this extra layer? Thanks Stack-O!

var Result =
from a in Db.Table
select new {TableData = a};

var ResultSorted = 
from a in Result
orderby a.TableData.Field
select new {All = a};

foreach(var RowSorted in ResultSorted)
{
    MessageBox.Show(RowSorted.All.TableData.ToString());
}
+3  A: 

You can use

var Result =
from a in Db.Table
select a;

var ResultSorted = 
from a in Result
orderby a.Field
select a;

foreach(var RowSorted in ResultSorted)
{
    MessageBox.Show(RowSorted.ToString());
}

Edit: The thing is that

select new {TableData = a};

creates a new anonymous type with a field called TableData, like this

class Tmp1
{
     TableType TableData {get; set;}
}

and

select new {All = a};

creates a new anonymous type with a field called TableData, like this

class Tmp2
{
     Tmp1 All {get; set;}
}

Edit 2:
If you select a directly you don't create the extra anonymous type, instead you return the TableType.

Albin Sunnanbo
A: 
var ResultSorted = 
   from a in Db.Table
   orderby a.Field
   select a.ToString();

Edit: Fixed, didn't see the first query. This should be identical now. There is no need to create anonymous objects all the time.

leppie
A: 

You are returning a new instance of an anonymous type in each of your LINQ queries:

select new {TableData = a}; 
select new {All = a}; 

What you are saying to the compiler is (in the first LINQ query), "Give me a new instance of an anoymous type. I want this anonymous type to have one property named TableData and I want the value for that property to be a."

If you simply return a instead of an anoymous type, you shouldn't need to go through the properties of the nested types to get the data. Try this:

var Result =  
from a in Db.Table  
select a;  

var ResultSorted =   
from a in Result  
orderby a.TableData.Field  
select a;  

foreach(var RowSorted in ResultSorted)  
{  
    MessageBox.Show(RowSorted.ToString());  
}  
Ben McCormack