如何在lambda表达式中使用局部变量

Rez*_*oan 7 c# linq lambda list

我有2个类的类型列表对象,

 class person
    {
        public string id { get; set; }
        public string name { get; set; }
    }

List<person> pr = new List<person>();
pr.Add(new person { id = "2", name = "rezoan" });
pr.Add(new person { id = "5", name = "marman" });
pr.Add(new person { id = "3", name = "prithibi" });

List<person> tem = new List<person>();
tem.Add(new person { id = "1", name = "rezoan" });
tem.Add(new person { id = "2", name = "marman" });
tem.Add(new person { id = "1", name = "reja" });
tem.Add(new person { id = "3", name = "prithibi" });
tem.Add(new person { id = "3", name = "prithibi" });
Run Code Online (Sandbox Code Playgroud)

现在,我必须从获得所有的ID "公关"具有的ListObject 没有进入奇数项"TEM" ListObejct.使用lamda.

要做到这一点我用过,

HashSet<string> inconsistantIDs = new HashSet<string>(pr.Select(p => p.id).Where(p => tem.FindAll(t => t.id == p).Count == 0 || tem.FindAll(t => t.id == p).Count % 2 != 0));
Run Code Online (Sandbox Code Playgroud)

它工作正常.

但是可以从我已经使用的代码看到tem.FindAll(T => t.id == p)的.Count之间的两次与comapre == 0%2!= 0.

有没有办法使用tem.FindAll(t => t.id == p).Count一次并将其保存到临时变量,然后将此变量与 == 0%2!= 0进行比较.

更简单地说,我只想在这里使用一次两个条件.

Ahm*_*IEM 14

使用语句 lambda而不是表达式 lambda

var inconsistantIDs = new HashSet<string>(
           pr.Select(p => p.id).Where(p => 
                  {
                    var count = tem.FindAll(t => t.id == p).Count;
                    return count == 0 || count % 2 != 0;
                  }
           ));
Run Code Online (Sandbox Code Playgroud)

  • 而不是`FindAll`我会使用`Count()`.前者需要为每个人创建一个新的集合. (3认同)