2017-06-26 124 views
0

我是初学linq的学习者。如何使用linq查询列表对象使用linq查询嵌套列表

var dbUserSettings = new List<UserSetting> { 
    new UserSetting { 
     UserId = "[email protected]", 
     Applications = new List<Application> { 
      new Application { 
       ApplicationID = "application123", 
       ApplicationName = "ProtocolArchiving", 
       Settings = new List<Setting> { 
        new Setting { 
         SettingId = "setting123", 
         SettingKey = "RefreshInterval", 
         SettingValue = "20", 
         IsActive = "true", 
         UpdatedOn = "2017-06-22", 
         SettingLabel = "PageRefresh" } } } } }, 

    new UserSetting { 
     UserId = "[email protected]", 
     Applications = new List<Application> { 
      new Application { 
       ApplicationID = "application345", 
       ApplicationName = "ProtocolArchiving", 
       Settings = new List<Setting> { 
        new Setting { 
        SettingId = "setting456", 
         SettingKey = "UploadSetting", 
         SettingValue = "20", 
         IsActive = "true", 
         UpdatedOn = "2017-06-22", 
         SettingLabel = "Upload" } } } } }, 
    new UserSetting { 
     UserId = "[email protected]", 
     Applications = new List<Application> { 
      new Application { 
       ApplicationID = "application678", 
       ApplicationName = "ProtocolArchiving", 
       Settings = new List<Setting> { 
        new Setting { 
         SettingId = "setting789", 
         SettingKey = "DownloadSetting", 
         SettingValue = "20", 
         IsActive = "true", 
         UpdatedOn = "2017-06-22", 
         SettingLabel = "Download" } } } } } 
    }; 

var response = dbUserSettings.Where(e => e.UserId == userID) 
        .Select(dbsetting => new UserSettingViewModel 
        { 
         SettingKey = dbsetting.Applications.Single<Setting>(s=> s ==) 

        }) 
        .ToArray(); 

我正在查询与我的userID匹配的settingkey。

编辑:

错过了一些事情提及。我在这里

SettingKey = dbsetting.Applications.FirstOrDefault().Select(sk => sk.Settings.FirstOrDefault()?.SettingKey); 

的错误是如下enter image description here

试过几件事情我的应用程序类看起来是这样的。

public class Application 
{ 
    public string ApplicationID { get; set; } 
    public string ApplicationName { get; set; } 
    public List<Setting> Settings { get; set; } 
} 
+1

'我正在查询与我的userID匹配的settingkey。'对你有好处,那究竟是什么问题? – EpicKip

+1

你的问题是什么?任何意外的结果?错误?请更具体地说明你想要做什么。 – HimBromBeere

+1

SettingKey = dbsetting.Applications.FirstOrDefault()?. Select(sk => sk.Settings.FirstOrDefault()?. SettingKey) –

回答

1

由于you're只是感兴趣的唯一Application每一个UserSetting我想你需要这个:

var response = dbUserSettings.Where(e => e.UserId == userID) 
    .Select(dbsetting => new UserSettingViewModel 
    { 
     SettingKey = dbsetting.Applications.FirstOrDefault()?.Settings.FirstOrDefault()?.SettingKey 
    }; 

这将只返回第一个(可能只)Setting内每个UserSetting内的第一个(也可能仅限于)Application。如果中间的任何列表(ApplicationsSettings)中的SettingKey将为null

+0

像一个魅力工作。 – dataEnthusiast