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

问题描述 投票:0回答:3

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

这里可以将一个人分配到多种类型的作品,并将其存储在PersonWorkTypes表中包含人员及其工作类型的详细信息。因此,我需要获取同时从事全职和自由职业的人员的名单。我已经尝试过

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

但是它返回空结果。

c# linq
3个回答
1
投票

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

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

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

或者,如果可以在此表中多次设置人员,则可以这样做:

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());

2
投票

您可以尝试这个

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中包含两种类型的人


0
投票
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);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.