繁体   English   中英

Linq 内同一列上的多个条件,其中

[英]Multiple condition on same column inside Linq where

如何编写 linq 查询以匹配表中同一列上的两个条件?

这里可以将一个人分配给多种类型的作品,它存储在PersonWorkTypes表中,其中包含人员及其工作类型的详细信息。

因此,我需要获取同时拥有全职和自由职业者的人员名单。

我努力了

people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")

但它返回一个空结果。

你可以试试这个

public class Person {
    public string Name {get;set;}
    public List<PersonWorkType> PersonWorkTypes {get;set;}
}

public class PersonWorkType {
    public string Type {get;set;}
}

public static void Main()
{
    var people = new List<Person>();
    var person = new Person { Name = "Toño", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" } } };
    var person2 = new Person { Name = "Aldo", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };
    var person3 = new Person { Name = "John", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };

    people.Add(person);
    people.Add(person2);        
    people.Add(person3);

    var filter = people.Where(p => p.PersonWorkTypes.Any(t => t.Type == "freelance") && p.PersonWorkTypes.Any(t => t.Type == "fulltime"));


    foreach(var item in filter) {
        Console.WriteLine(item.Name);
    }
}

这将返回包含 PersonWorkTypes 中两种类型的人员

w.worktype=="freelance"
w.worktype=="fulltime"

这些是相互排斥的,因此不能同时满足您的 AND(&&) 运算符。

我推断每个人的表中有两个(或更多)不同的行,一个用于他们所做的每种类型的工作。 如果是这样,Where() 方法将逐行检查您的列表,并且无法检查列表的两个不同元素以查看 Alice(例如)是否都有“自由职业者”的条目和“全职”条目作为列表中的两个不同元素。 不幸的是,我想不出在单个查询中执行此操作的简单方法,但是这样的事情可能会起作用:

var fulltimeWorkers = people.Where(w=>w.worktype=="fulltime");
var freelanceWorkers = people.Where(w=>w.worktype=="freelance");
List<Person> peopleWhoDoBoth = new List<Person>();
foreach (var worker in fulltimeWorkers)
{
   if (freelanceWorkers.Contains(worker)
      peopleWhoDoBoth.Add(worker);
}

这可能不是最有效的方法,但对于小型数据集,这无关紧要。

正如已经说过的, &&运算符的意思是,必须满足两个条件。 因此,在您的情况下,这意味着您希望freelanceworktype fulltime类型同时使用,这是不可能的:)

很可能您希望员工的工作类型为freelancefulltime ,因此您的条件应该是:

people.Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")

或者,如果 person 可以在此表中多次设置,那么您可以执行以下操作:

people
  .Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")
  // here I assume that you have name of a person,
  // Basically, here I group by person
  .GroupBy(p => p.Name)
  // Here we check if any person has two entries,
  // but you have to be careful here, as if person has two entries
  // with worktype freelance or two entries with fulltime, it
  // will pass condition as well.
  .Where(grp => grp.Count() == 2)
  .Select(grp => grp.FirstOrDefault());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM