获取许多对象列表的属性

时间:2018-01-12 15:58:46

标签: c# entity-framework entity-framework-core

我有以下对象:

public class User {
  public Int32 Id { get; set; }
  public List<Language> Languages { get; set; }
  public List<Skill> Skills { get; set; }
}

public class Language {
  public Int32 Id { get; set; }
  public String Name { get; set; }
}

public class Skill {
  public Int32 Id { get; set; }
  public String Name { get; set; }
}

然后我有以下查询:

List<UserModel> models = context.Users.Select(x =>
  new UserModel {
    Id = x.Id,
    Names = ????
  }).ToList();

我需要服用:
1.第一种用户语言的名称(如果有的话) 2.前2个用户技能的名称(如果有)。

并将这些名称添加到UserModel.Names,其中UserModel为:

public class UserModel {
  public Int32 Id { get; set; }
  public List<String> Names { get; set; }
}

我如何在查询中执行此操作?

3 个答案:

答案 0 :(得分:3)

您可以使用TakeConcat。请尝试以下代码:

List<UserModel> models = context.Users.Select(x =>
  new UserModel {
    Id = x.Id,
    Names = x.Languages.Take(1).Select(y=>y.Name)
     .Concat(x.Skills.Take(2).Select(y => y.Name)).ToList()
  }).ToList();

答案 1 :(得分:0)

 Func<User, IEnumerable<string>> getUserLanguageNames = user => user.Languages.Select(language => language.Name);
 Func<User, IEnumerable<string>> getUserSkillNames = user => user.Skills.Select(skill => skill.Name);
 List<UserModel> models = context.Users.Select(user => new UserModel { Id = user.Id, Names = getUserLanguageNames(user).Concat(getUserSkillNames(user)).ToList() }).ToList();

答案 2 :(得分:0)

您可以使用拍摄跳过

var ListUserModel = context.Users.Select(u => new UserModel { Id = u.Id, Names 
= new List<string> { u.Languages.FirstOrDefault().ToString(), 
u.Skills.Take(1).ToString(), u.Skills.Skip(1).Take(1).ToString() } });