LINQ对实体的查询将属性的值附加到一个变量上

本文关键字:一个 变量 查询 实体 属性 LINQ | 更新日期: 2023-09-27 18:06:18

我有这样的查询:

var sole = SoleService.All().Where(c => c.Status != 250)
               .Select(x => new { 
                    ID = x.ID, Code = new {CodeName = x.Code + x.Country}, 
                    Name = x.Name 
               })
               .Distinct()
               .OrderBy(s => s.Code);

像这样,它给了我一个错误。我想要的是像连接字符串一样组合CodeCountry,这样我就可以为我的数据源使用新变量。比如- 001France

p。S

我正在使用和正在工作的是:

var sole = SoleService.All().Where(c => c.Status != 250)
               .Select(x => new { 
                   ID = x.ID, Code = x.Code, Name = x.Name, Country = x.Country })
               .Distinct()
               .OrderBy(s => s.Code);

所以我需要的是修改这个查询,所以我可以使用Code +Country作为一个变量。以上只是我的尝试,我认为会工作。

LINQ对实体的查询将属性的值附加到一个变量上

听起来像:

 var sole = SoleService.All().Where(c => c.Status != 250)
                .AsEnumerable()
                .Select(x => new { 
                                ID = x.ID, 
                                Code = x.Code + x.Country, 
                                Name = x.Name
                                })
                .Distinct()
                .OrderBy(s => s.Code);

根本不需要内部匿名类型。如果您正在EF上工作,不支持正弦字符串+,请在执行select之前调用AsEnumerable

您不能按s.Code排序,因为它是匿名类型的实例。我选

var sole = SoleService.All().Where(c => c.Status != 250)
        .Select(x => new { ID = x.ID, Code = new {CodeName = x.Code + x.Country}, Name = x.Name })
        .Distinct()
        .OrderBy(s => s.Code.CodeName);

尝试添加。tostring(),因为问题应该是+运算符相信您尝试添加数字属性…

Like that:

 var sole = SoleService.All().Where(c => c.Status != 250)
        .Select(x => new { ID = x.ID, Code = new {CodeName = x.Code.ToString() + x.Country.ToString()}, Name = x.Name })
        .Distinct()
        .OrderBy(s => s.Code);