我是初学者,学习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();
我正在查询与我的userID匹配的settingkey。
编辑:
错过了几件事要提。我在这里尝试了一些事情
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; }
}
答案 0 :(得分:1)
由于您只对每Application
UserSetting
感兴趣,我认为您需要这个:
var response = dbUserSettings.Where(e => e.UserId == userID)
.Select(dbsetting => new UserSettingViewModel
{
SettingKey = dbsetting.Applications.FirstOrDefault()?.Settings.FirstOrDefault()?.SettingKey
};
这将只返回每个Setting
内的第一个(也可能是唯一的)Application
中的第一个(也可能只是)UserSetting
。如果其间的任何列表为空(Applications
或Settings
)SettingKey
将为null
。