如何在 Linq 查询中使用子字符串#

How to use Substring in Linq query c#

我有这个查询,我想检索地址的第 2 个字符。所以我尝试了这个查询:

    var result = (from c in context.DB_CLIENT
        join ad in context.DB_ADRESSE on c.CLI_ADR_FACTURATION equals ad.ADR_ID
        select new { c.CLI_NOM,ad.ADR_ADRESSE3.Substring(0,2)});

但是我得到了这个错误:

Compiler Error CS0746
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

你能帮帮我吗?

您必须使用 c.ADR_Address3 进入 select 列,并且您正在 select 浏览 ad,这是不可用的。如果这 table 不同于您需要指定 table 名称

var result = (from c in context.DB_CLIENT
select new { c.CLI_NOM,c.ADR_ADRESSE3.Substring(0,2)});

如果您使用方法而不是仅使用 属性,则需要为匿名类型中的 属性 命名。

var result = from c in context.DB_CLIENT
             select new { 
                 c.CLI_NOM,  // property name will be used in the anonymous type
                 ADR_ADRESSE3_Prefix = ad.ADR_ADRESSE3.Substring(0,2)
             });

当您从表达式

中赋值时,编译器无法推断出 属性 名称

MSDN:

If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name for a property that is being initialized with an expression

我认为 ad 是局部变量或打字错误,实际上意味着 c

您可以使用 let 关键字来定义短地址并将其与对象初始值设定项一起使用。

 var result = (from c in context.DB_CLIENT
               join ad in context.DB_ADRESSE on c.CLI_ADR_FACTURATION equals ad.ADR_ID
               let address = ad.ADR_ADRESSE3.Substring(0,2)
               select new { CLI_NOM = c.CLI_NOM, Address = address});