这是我第一次使用LINQ而我还没有真正理解它。
我试图通过一个例子来理解它,但我需要一些帮助。
我创建了一个“人”类:
class Person
{
private string name { get; set; }
private int age { get; set; }
private bool parent { get; set; }
private bool child { get; set; }
public Person(string name, int age, bool parent, bool child)
{
this.name = name;
this.age = age;
this.parent = parent;
this.child = child;
}
}
我创建了一个“人物”列表:
people.Add(new Person("Joel", 12, false, true));
people.Add(new Person("jana", 22, false, false));
people.Add(new Person("Stefan", 45, true, false));
people.Add(new Person("Kurt", 25, false, false));
people.Add(new Person("Sebastian", 65, true, false));
people.Add(new Person("George", 14, false, true));
people.Add(new Person("Noel", 50, true, false));
现在我想把所有被设定为父母的人都赶出去。 但我被困在这里:
var parents = people.Where()
答案 0 :(得分:6)
linq语句应为
var parents = people.Where(x => x.parent);
并将private bool parent { get; set; }
更改为public bool parent { get; set; }
答案 1 :(得分:4)
var peopleWithParents = people.Where(x => x.parent == true).ToList();
尽管可能需要一段时间才能解决问题,但语法非常简单,并且使用起来非常舒适。请记住,' where'充当过滤器,并选择'充当投射。请记住,您需要将属性公开显示。如果你愿意,你可以保持私人的私人。您甚至可以引入一种方法来检查父项是否存在,并在lambda中调用它。
让我们假设你的班级更复杂。
class Person
{
public string name { get; private set; }
public int age { get; private set; }
public Person parent { get; private set; }
public bool child { get; private set; }
public bool HasParent()
{
return parent != null;
}
public Person(string name, int age, Person parent, bool child)
{
this.name = name;
this.age = age;
this.parent = parent;
this.child = child;
}
}
您可以执行以下操作来获取代表所有父母的人物对象列表:
var parents = people.Where(x => x.parent != null).Select(x => x.parent).ToList();
或
var parents = people.Where(x => x.HasParent()).Select(x => x.parent).ToList();
您也不需要使用' x'这封信只在每个条款的范围内;甚至可以按年龄命令这些父母:
var parents = people.Where(y => y.HasParent()).Select(z => z.parent).OrderBy(x => x.age).ToList();
也许您想从上面的集合中获得最老的父母:
var oldestParent = parents.OrderByDescending(x => x.age).FirstOrDefault();
if (oldestParent != null)
{
Console.WriteLine($"{oldestParent.name} is the oldest, at {oldestParent.age}");
}
您可以在查询中组合多个检查:
var parentsOfPeopleWithChildren = people.Where(x => x.parent != null && x.child).Select(x => x.parent).ToList();
另请注意,在C#中,您通常会将第一个属性字母大写。例如:
public bool Child { get; private set; }
答案 2 :(得分:1)
LINQ
非常简单:
var query = people.Where(x => x.parent);
但是,由于访问修饰符,您的parent
可能无法访问。
如果您不希望在声明后从外部更改它(这可能是您通过构造函数的参数声明属性的原因)。我建议你使用public { get; private set; }
class Person
{
public string name { get; private set; }
public int age { get; private set; }
public bool parent { get; private set; }
public bool child { get; private set; }
public Person(string name, int age, bool parent, bool child)
{
this.name = name;
this.age = age;
this.parent = parent;
this.child = child;
}
}