1

语境

我从这样的数据库中检索网站列表:

DashboardEntities dashboardDB = new DashboardEntities();

var sites = dashboardDB.Instances
    .Select(attr => new SiteModel
        {
            server = attr.server,
            pool = attr.pool,
            url = attr.url,
            version = attr.version,
            client = ???
        })
    .ToList();

return sites;

对于client,我需要从 url 中获取一个子字符串,如下所示:

String client = "";

Regex rgx = new Regex(@"\.[a-z-./]+");
client = rgx.Replace(attr.url, "");

rgx = new Regex("formation-");
client = rgx.Replace(client, "");

问题

如何使用正则表达式对我的 LINQ 查询进行此字符串操作?

4

5 回答 5

2

您甚至不需要第二次替换的正则表达式。您可以使用静态重载将其作为单个表达式执行:

client = Regex.replace(attr.url, @"\.[a-z-./]+", "").Replace("formation-", "")
于 2012-07-16T15:27:34.003 回答
2

根据 Guffa 和 RePierre 的说法:

DashboardEntities dashboardDB = new DashboardEntities();

var sites = dashboardDB.Instances
    .Select(attr => new SiteModel
        {
            url = attr.url,
            server = attr.server,
            pool = attr.pool,
            version = attr.version,
            client = attr.url
        })
    .ToList();

sites.ForEach(attr => attr.client = Regex.Replace(attr.client, @"\.[a-z-./]+", "").Replace("formation-", ""));
于 2012-07-17T12:03:19.540 回答
1

你不能以目前的形式拥有它。正则表达式部分不会有已知的 SQL 翻译。但是,您可以在.ToList()调用 后将其添加为后续选择。

...   .ToList()
      .Select(
          z => z.client = new Regex(@"\.[a-z-./]+")
               .Replace(z.attr.url, "").Replace("formation-", "")
      )

将其视为伪代码,但一般方法应该能够完成它。然后你只需要client = ""在初始选择中进行设置。

编辑:作为旁注,“形成”部分真的不需要是正则表达式。一个简单的字符串替换就足够了,而且会更快。

于 2012-07-16T15:24:47.990 回答
1

不幸的是,您将无法将正则表达式处理逻辑直接发送到数据库;您需要从数据库中获取 url,然后遍历列表以从 url 获取客户端数据。

DashboardEntities dashboardDB = new DashboardEntities();  
var sites = dashboardDB.Instances 
    .Select(attr => new SiteModel 
    { 
        server = attr.server, 
        pool = attr.pool, 
        url = attr.url, 
        version = attr.version, 
        client = attr.url    // load the url for further processing
    }) 
    .ToList();
// iterate over the list and get client data from the url
sites.ForEach(ite => item.client = GetSubstring(item.client)); 
return sites; 

该方法GetSubstring封装了正则表达式处理逻辑。

private string GetSubstring(string url)
{
    String client = "";        
    Regex rgx = new Regex(@"\.[a-z-./]+");        
    client = rgx.Replace(attr.url, "");        
    rgx = new Regex("formation-");        
    client = rgx.Replace(client, ""); 
    return client;
}
于 2012-07-16T15:25:36.280 回答
1

可能有更好的方法,但是:

Regex rgx1 = new Regex(@"\.[a-z-./]+");
Regex rgx2 = new Regex("formation-");

DashboardEntities dashboardDB = new DashboardEntities();

var sites = dashboardDB.Instances
    .Select(attr => new SiteModel
        {
            server = attr.server,
            pool = attr.pool,
            url = attr.url,
            version = attr.version,
            client = rgx2.Replace(rgx1.Replace(attr.url,""),"")
        })
    .ToList();

return sites;
于 2012-07-16T15:27:01.723 回答