2010-01-02 121 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