2010-01-02 209 views
3

在WPF應用程序中,我有一個通過數據綁定與ListView連接的Observable集合。我想從LINQ到SQL查詢填充這個Observable Collection,但沒有成功。實際上,我的代碼甚至不能編譯(我用註釋指出了問題行)。如何將LINQ添加到SQL查詢結果到Observable集合?

底層Observable Collection類的結構與我嘗試獲取查詢的SQL表的結構類似。

請問我的方法有什麼問題?

這裏是我的代碼部分:

ObservableCollection<ShowsQu> _ShowQuCollection = 
      new ObservableCollection<ShowsQu>(); 

    public ObservableCollection<ShowsQu> ShowQuCollection 
    { get { return _ShowQuCollection; } } 

    public class ShowsQu 
    { 
     public string ShowCode { get; set; } 
     public DateTime Date { get; set; } 
     public TimeSpan Time { get; set; } 
     public string Description { get; set; } 
    } 

    private void VisualizeAllShows() 
    { 

     MyfirstdbDataContext context = new MyfirstdbDataContext(); 
     _ShowQuCollection.Clear(); 

     var sh = from p in context.Shows select p; 

     foreach (var p in sh) 
      _ShowCollection.Add(new ShowsQu 
      { 
       Date = sh.Date, //here is compile-time error 
       Time = sh.Time, //here is compile-time error 
       Description = sh.Description //here is compile-time error 
      }); 
     }   
    } 

回答

2

SUBST sh/psh是查詢,p是當前迭代項):

foreach (var p in sh) { 
    _ShowCollection.Add(new ShowsQu { 
     Date = p.Date, 
     Time = p.Time, 
     Description = p.Description 
    }); 
} 

順便說一句,你可以只使用foreach(var p in context.Shows) {...}這裏。

+0

是的。非常感謝!有用。多麼愚蠢的mitake我做了,並且不能幾小時本地化它! – rem 2010-01-02 11:20:54

+0

也感謝你的最後一行的提示 – rem 2010-01-02 11:26:22

+0

新鮮的眼睛通常是有用的; -p – 2010-01-02 20:55:58

相關問題