使用 linq 查询嵌套列表
Posted
技术标签:
【中文标题】使用 linq 查询嵌套列表【英文标题】:Querying a nested list using linq 【发布时间】:2017-11-29 00:03:11 【问题描述】:我是初学者学习 linq。如何使用 linq 查询列表对象
var dbUserSettings = new List<UserSetting>
new UserSetting
UserId = "abcxyz@123",
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 = "abcxyz@345",
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 = "abcxyz@567",
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();
我正在查询与我的用户 ID 匹配的设置键。
编辑:
错过了几件事要提。我在这里尝试了几件事
SettingKey = dbsetting.Applications.FirstOrDefault().Select(sk => sk.Settings.FirstOrDefault()?.SettingKey);
报错如下
我的应用程序类如下所示。
public class Application
public string ApplicationID get; set;
public string ApplicationName get; set;
public List<Setting> Settings get; set;
【问题讨论】:
I am querying for settingkey which matches with my userID.
对你有好处,实际上是什么问题?
你的问题是什么?有什么意想不到的结果吗?错误?请更具体地说明您要做什么。
SettingKey = dbsetting.Applications.FirstOrDefault()?.Select(sk => sk.Settings.FirstOrDefault()?.SettingKey)
我认为 select many 是您正在寻找的东西。 ***.com/questions/958949/…
@LaurentLequenne 这甚至不会编译,因为FirstOrDefault
返回一个没有Select
的Application
实例。
【参考方案1】:
因为您只对每个 UserSetting
的唯一一个 Application
感兴趣,我想您需要这个:
var response = dbUserSettings.Where(e => e.UserId == userID)
.Select(dbsetting => new UserSettingViewModel
SettingKey = dbsetting.Applications.FirstOrDefault()?.Settings.FirstOrDefault()?.SettingKey
;
这将只返回每个UserSetting
内的第一个(并且可能也是唯一的)Application
中的第一个(可能是唯一的)Setting
。如果两者之间的任何列表为空(Applications
或 Settings
),则 SettingKey
将为 null
。
【讨论】:
以上是关于使用 linq 查询嵌套列表的主要内容,如果未能解决你的问题,请参考以下文章