Where()表示值列表

时间:2017-04-05 15:34:13

标签: c# linq

是否有可能在没有foreach的情况下将下面的内容写成linq语句,只需将emailList变为linq查询?

List<EmailFilter> el = new List<EmailFilter>();

foreach(string email in emailList) // emailList is string list of available emails
{
    el.AddRange( db.EmailFilters.Where(x => x.Email == email) ).ToList();
}

所以我会使用单个linq查询填充el

4 个答案:

答案 0 :(得分:4)

因此,您希望获取EmailFilter中包含Email emailList的每个List<EmailFilter> el = db.EmailFilters.Where(x => emailList.Contains(x.Email)).ToList(); 。在这种情况下,LINQ还可以帮助提高可读性:

List<EmailFilter> el  = db.EmailFilters.Where(x => emailList.Contains(x.Email) ).ToList(); 

答案 1 :(得分:4)

您可以尝试:

Use TempDB
GO

CREATE PROCEDURE xspValidate(@e varchar(128))
AS
BEGIN
SELECT 
    CASE
        WHEN @e like '_%_@_%.__%'
        AND NOT (
            @e like '%[^-A-Za-z0-9_@.]%'
            OR @e like '%[.@][.@]%'
            OR @e LIKE '%@%@%'
            )
            THEN 'Valid'
        ELSE 'Wrong'
    END
END

GO


EXEC xspValidate 'bob@ray.com'  -- valid
EXEC xspValidate 'bob@q.com'    -- valid
EXEC xspValidate 'b*b@ray.com'  -- wrong
EXEC xspValidate 'A@b.C'        -- wrong
EXEC xspValidate 'Alpha@@numeric.com'   -- wrong
EXEC xspValidate 'Alpha@.com'   -- wrong

答案 2 :(得分:0)

你也可以把它写成一个连接

var el = from emailFilter in db.EmailFilters
    join email in emailList on emailFilter.Email equals email
    select emailFilter;

答案 3 :(得分:0)

如果el是一个列表,您可以使用AsEnumerable将它与linq中的数据库表连接。

var result= from p in db.EmailFilters
            join s in el.AsEnumerable() on p.Email=el.Email
             select p;