这是我的人index.cshtml的输出。我不知道如何在我的index.cshtml表中加入sql linq,有什么想法吗?
name allapartments active
john 1, 2, 3 no
mary 1 yes
公寓对象
id name
1 LA downtown apts
2 NYC downtown apts
想要输出:
name allapartments active
john LA downtown apts, NYC downtown apts no
mary LA downtown apts yes
人员控制器
public ActionResult Index()
{
var apartments = db.Apartments;
var result = from item in Persontable
where apartments.All(x => item.allapartments.Contains(x))
select item;
}
答案 0 :(得分:0)
我想出了这个
void Main()
{
var personTables = new List<Persontable>{
new Persontable{Name = "John", AllApartments = new List<int>{1, 2, 3}, Active = false},
new Persontable{Name = "Mary", AllApartments = new List<int>{1}, Active = true},
};
var apartments = new List<Apartment>{
new Apartment { Id = 1, Name = "LA downtown apts"},
new Apartment { Id = 2, Name = "NYC downtown apts"},
};
var result = personTables.Select( p => new PersontableAparment{
Name = p.Name,
AllApartmentsNames = apartments.Where(a => p.AllApartments.Contains(a.Id)).Select(x => x.Name).ToList(),
Active = p.Active,
});
}
public class Persontable
{
public string Name { get; set;}
public List<int> AllApartments { get; set;}
public bool Active {get; set;}
}
public class Apartment
{
public int Id {get; set;}
public string Name {get; set;}
}
public class PersontableAparment
{
public string Name { get; set; }
public List<string> AllApartmentsNames { get; set; }
public bool Active { get; set; }
}
您可以结帐现场演示here。我假设
name allapartments active
john 1, 2, 3 no
mary 1 yes
是Persontable表中的数据。请注意,我使用PersontableApartment
类来建模您想要的输出。如果您觉得有用,请将其作为已接受的答案。