Linq将所选数据插入到ObservableCollection中

时间:2014-09-29 11:26:43

标签: c# linq

如何将linq查询插入ObservableCollection数据结构?看看我的代码片段:

    var server = from e in _fileElement.Elements("computerprefix")
        where e.Attribute("name") != null
        select new ServersLogins
        {
            Server = e.Attribute("name").Value,
            Logins = from i in e.Elements("user")
                select new ObservableCollection<Login>
                {
                    User = i.Attribute("name"),
                    Password = i.Attribute("password")
                }
        };

我的错误信息

'System.Collections.ObjectModel.ObservableCollection<CustomCopyNas.Models.Login>' does not contain a definition for 'Password'  D:\c#\Samples\CustomCopyNas\CustomCopyNas\Views\LoginViewModel.cs
'System.Collections.ObjectModel.ObservableCollection<CustomCopyNas.Models.Login>' does not contain a definition for 'User'  D:\c#\Samples\CustomCopyNas\CustomCopyNas\Views\LoginViewModel.cs

我怎样才能以正确的方式做到?

1 个答案:

答案 0 :(得分:5)

试试这个:

var server = from e in _fileElement.Elements("computerprefix")
             where e.Attribute("name") != null
             select new ServersLogins
             {
                 Server = e.Attribute("name").Value,
                 Logins = new ObservableCollection(
                              from i in e.Elements("user")
                              select new Login
                              {
                                  User = i.Attribute("name"),
                                  Password = i.Attribute("password")
                              })
             };