这是我们的目标:获取一个通用的人员列表,并在我的模型中按男性,女性和儿童排序...... 我也为了这个网站和我的隐私而重命名了一些东西。请关注下面的lambda表达式!谢谢!
我收到此错误:
无法从
System.Collections.Generic.IEnumerable<bool>
转换为System.Collections.Generic.IEnumerable<Project1.DataClasses.DataObjects.People>
PeopleModel:
public List< People> Men { get; set; }
public List< People> Women { get; set; }
public List< People> Kids { get; set; }
public List< People> Babies { get; set; }
控制器:
public ActionResult GetPeople(PeopleModels Peoples)
{
List<People> listPeoples = new List<People>();
listPeoples = DataClass.GetAllPeoples();
// this is the code I cannot get to work.
var men = listPeoples .Select(m => m.Sex == "M");
Peoples.Men = men.ToList<People>();
// Women, Children too..
return View("Employees", Peoples);
}
答案 0 :(得分:7)
您正在寻找Where
声明。
// Get People wher the Sex = "M"
Peoples.Men = listPeoples.Where(m => m.Sex == "M").ToList();
答案 1 :(得分:4)
您目前只选择m.Sex
属性,并尝试将其列表分配给List<People>
,这就是错误原因。你可以这样做:
Peoples.Men = listPeoples.Where(m => m.Sex == "M").ToList();
此外,您不需要Tolist<People>()
,简单ToList()
就可以完成这项工作。
答案 2 :(得分:2)
您不了解Linq查询的基础知识。该 “选择”语句必须投影结果。例如:
var a = new List<string>{"ab", "abc", "abcd"};
var b = a.Select(x=>x.Length).ToList();
这里发生的是选择所有“a”元素的长度,并将它们保存到变量b,现在List<int>
包含{2,3,4}
你需要的是“Where”语句,它通过集合中的谓词过滤对象(任何IEnumerable对象)
var c = a.Where(x=>x.Length<4).Select(x=>x.Length).ToList();
另一种语法:
var c = (from element in a
where element.Length<4
select x=>Length).ToList();
我们说来自 元素 列表中的 > 长度少于4个字符,选择所有长度,将列入并分配给 c 变量
建议您阅读有关主题的更多信息并查看these示例
答案 3 :(得分:1)
你的男士系列包含布尔类型的物品。
var men = listPeoples .Select(m => m.Sex == "M"); // returns a boolean collection satisfying the condition
Peoples.Men = listPeoples .Where(m => m.Sex == "M").ToList(); // This should be what you want
您也可以
var men = listPeoples .Where(m => m.Sex == "M");
Peoples.Men = men.ToList();
答案 4 :(得分:0)
使用组,您可以将每种类型都添加到自己的集合中:
var grouped = from person in people
group person by person.Type into g
select new {Key = g.Key, people = g};
唯一的问题是选择每个集合,这是我到目前为止最好的:
List<Person> men = new List<Person>(), women = new List<Person>(), children = new List<Person>(), babies = new List<Person>();
foreach (var persons in grouped)
{
switch (persons.Key)
{
case PersonType.Male: men = persons.people.ToList(); break;
case PersonType.Female: women = persons.people.ToList(); break;
case PersonType.Child: children = persons.people.ToList(); break;
case PersonType.Baby: babies = persons.people.ToList(); break;
}
}