如何格式化linq表达式中的字符串

本文关键字:字符串 表达式 linq 格式化 | 更新日期: 2023-09-27 18:26:22

给定以下代码

IQueryable<string> customers = 
    from Customers in db.Customers
    where Customers.CstCompanyName.Contains(prefixText) && Customers.CstInactive == false
    select Customers.CstCompanyName + " (Phone: " + Convert.ToInt64(Customers.CstPhone).ToString("###-###-#### ####") + ")";

这是对我的实体框架的调用。我正在从数据库中返回一个电话号码。我正在尝试将其格式化为给定的格式字符串。不幸的是,当我运行此程序时,我收到以下错误:

LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

所以我的问题是如何将这个数据库对象作为格式化字符串返回?

谢谢!

如何格式化linq表达式中的字符串

我会在数据库中执行查询,但在本地格式化

var customers = db.Customers
                  .Where(c => c.CstCompanyName.Contains(prefixText))
                  .Select(c => new { c.CstCompanyName, c.CstPhone })
                  .AsEnumerable() // Switch to in-process
                  .Select(c => c.CstCompanyName + 
                               " (Phone: " +            
                               Convert.ToInt64(Customers.CstPhone)
                                      .ToString("###-###-#### ####") + ")");

我不确定这是否是正确的方式,但我想使用我喜欢的东西。如果您正在使用实体框架并加载它,那么您可以将String.Format放置在LINQ查询中。

Dim ds as Entity = New Entity()
    ds.FinancialInstitutionTransactions.OrderByDescending(Function(c) c.TransID).Load()
    Dim openLoad = From tr In ds.FinancialInstitutionTransactions.Local
                   Select TransDate = String.Format("{0:d}", tr.Date),
                   tr.Number,
                   tr.ToFrom,
                   Debit = If(tr.Debit = 0, " ".ToString(), String.Format("{0:N}", tr.Debit).ToString()),
                   Credit = If(tr.Credit = 0, " ".ToString(), String.Format("{0:N}", tr.Credit).ToString())

您需要引用System.Data.Entity才能加载,但是可以很容易地以任何方式格式化结果。

我希望这能帮助到别人。我知道这是在vb.net中,但转换成c#并不难。