C# 使用 LINQ 检查某个值是否在集合中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1182227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a value is in a collection with LINQ
提问by Kris-I
I have a class "Employee", this has an IList<> of "TypeOfWork".
我有一个“员工”类,它有一个“TypeOfWork”的 IList<>。
public class Employee
{
public virtual IList<TypeOfWork> TypeOfWorks { get; set; }
}
public class TypeOfWork
{
public virtual Customer Customer { get; set; }
public virtual Guid Id { get; set; }
public virtual string Name{ get; set; }
public virtual bool IsActive{ get; set; }
}
before saving, I'd lile to know if "typeofwid" (a Guid) is already in the "TypeOfWorks" collection.
在保存之前,我很想知道“typeofwid”(一个 Guid)是否已经在“TypeOfWorks”集合中。
I tried this :
我试过这个:
var res = from p in employee.TypeOfWorks
where p.Id == new Guid("11111111-1111-1111-1111-111111111111")
select p ;
and tried this :
并尝试了这个:
bool res = employee.TypeOfWorks.Where(f => f.Id == new Guid("11111111-1111-1111-1111-111111111111")).Count() != 0;
in the "Immediate Window" of Visual Studio but I receive the error : Expression cannot contain query expressionsin both case
在 Visual Studio 的“立即窗口”中,但我收到错误:表达式在两种情况下都不能包含查询表达式
Do you have an idea ?
你有想法吗 ?
Thanks,
谢谢,
采纳答案by JoshJordan
Just what the error says. You can't use LINQ queries in the Immediate Window because they require compilation of lambda functions. Try the first line in your actual code, where it can be compiled. :)
正是错误所说的。不能在立即窗口中使用 LINQ 查询,因为它们需要编译 lambda 函数。试试你的实际代码中的第一行,它可以被编译。:)
Also, to get this all done in one line, you can use the LINQ "Any" operator, like so:
此外,要在一行中完成这一切,您可以使用 LINQ "Any" 运算符,如下所示:
if( ! employee.TypeOfWorks.Any(tow => tow.Id == theNewGUID) )
//save logic for TypeOfWork containing theNewGUID
回答by CodeRedick
I think either of those work, actually. Keep in mind Visual Studio can't handle Linq Queries in the watch window either, so I suspect the error you saw is more of a Visual Studio problem than the code not working.
实际上,我认为其中任何一项都有效。请记住,Visual Studio 也无法处理监视窗口中的 Linq 查询,因此我怀疑您看到的错误更像是 Visual Studio 问题,而不是代码不起作用。
回答by Francis B.
Try this code to get the count of typeofwork not initialized.
尝试使用此代码来获取未初始化的 typeofwork 的计数。
if(employee.TypeOfWorks
.Count(f => f.Id != new Guid("11111111-1111-1111-1111-111111111111")) != 0)
{
//do something
}
回答by Blackspy
how about
怎么样
Guid guid = Guid.NewGuid("11111111-1111-1111-1111-111111111111");
var res = from p in employee.TypeOfWorks
where p.Id == guid
select p ;
The problem is constructing the guid - otherwise the linq queries should work