2009-12-09 118 views
0

如何查詢使用select new填充/創建的集合?如何查詢匿名類型集合?

我有這個BindingSource

this.bindingSource.DataSource = 
    from row in db.Table 
    select new 
    { 
     name = row.Name + row.Num.ToString() 
    }; 

我想查詢它像我這樣做與其他BindingSources:

var query = from row in (IEnumerable<Table>)anotherBindingSource.List 
      where row.name == "asd" 
      select row; 

由於BindingSource的包含匿名類型我得到這個錯誤:

Unable to cast object of type 'System.Data.Linq.SortableBindingList 1[<>f__AnonymousType8 15 etc. etc. to type 'System.Collections.Generic.IEnumerable`1[Table]'.

我該怎麼辦?

+0

嘗試在內部級別鑄造,我的意思是... select(Table)row;在第三行。 – 2009-12-09 14:23:39

回答

4

那麼,不確定你在這裏試圖做什麼,而是一個匿名類型!=一個Table對象。異常表明你正在試圖將一個匿名類型的IEnum(一個編譯器生成的類名稱奇怪)轉換爲Table類型的IEnum。

您不能在C#中投射類型。例如,您不能這樣做:
​​
您不能將任何類型不是表格,或者從表格延伸到表格

所以你問的是不可能的。你應該退後一步,問一個關於你想要完成什麼的更一般的問題。


一些更多的匿名類型......他們才真正有它們所定義的方法的範圍之內的意思。看起來你可能會從方法調用返回anon類型枚舉,然後嘗試排序。這是行不通的,因爲一旦匿名類型離開方法範圍,它被認爲(至少通過intellisense)成爲一個對象,並且獲得其屬性的唯一方法就是使用反射。

如果你的例子不只是一個簡化版本,你可以直接跳過完全的匿名類型...

this.bindingSource.DataSource = 
    from row in db.Table 
    select row.Name + row.Num.ToString(); 

這是一個IEnumerable,可正是如此進行查詢:

var query = from row in anotherBindingSource 
      where row.StartsWith("asd") 
      select row; 

但是它看起來並不像你完成了很多在這一切......


你不能屈在它們被定義的範圍之外的匿名類型。

這工作:

​​

這不:

public class Anonymous 
{ 
    public IEnumerable GetMyDurrs(Hurr hurr) 
    { 
    return from x in Hurr select new { x.Durr }; 
    } 

    public IEnumerable WeedMyDurrs(Hurr hurr, string value) 
    { 
    // this won't compile 
    return from x in GetMyDurrs(hurr) where x.Durr == value select x; 
    } 
} 

第二個例子不能編譯,因爲匿名類型被另一個範圍內定義。

讓這個工作的唯一方法是定義一個類型。

public class Anonymous 
{ 
    public IEnumerable<Anonymous.MyDurr> GetMyDurrs(Hurr hurr) 
    { 
    return from x in Hurr select new MyDurr { Durr = x.Durr }; 
    } 

    public IEnumerable<Anonymous.MyDurr> WeedMyDurrs(Hurr hurr, string value) 
    { 
    // this won't compile 
    return from x in GetMyDurrs(hurr) where x.Durr == value select x; 
    } 

    public class MyDurr { public string Durr {get;set;} } 
} 
+0

好吧,忘記bindingSource的東西。你如何查詢使用選擇新建的集合?例如:var productQuery = from prod in products select new {prod.Color,prod.Price}; 你如何查詢「productQuery」?我的意思是使用... ...在哪裏。 – dstr 2009-12-09 14:40:02

+1

@Armagan:'productQuery.Where(p => p.Color == someColor && p.Price == somePrice);'或'var anotherQuery =從productQuery中的p其中p.Color == someColor && p.Price == somePrice選擇p;'。 – jason 2009-12-09 14:43:09