繁体   English   中英

在LINQ查询中将Int连接为字符串

[英]Concatenate Int to String in LINQ Query

我有以下LINQ查询。

var providers = from c in Repository.Query<Company>()
                where !c.IsDeleted
                select new { c.Description, Id = "C" + c.Id };

我正在尝试将ID连接到“ C”。 因此,例如,如果c.Id为35,则结果应为“ C35”。

这显然不起作用,因为您不能在字符串中添加整数( c.Id )。 我可以使用C.使用string.Format()或转换类型轻松解决此问题。 但是如何在LINQ中做到这一点?

如果仅在准备结果时需要.NET功能(而不是过滤,则应在RDBMS端进行此操作,以避免在内存中带入过多数据),通常的技巧是使用AsEnumerable在内存中完成转换方法:

var providers = Repository.Query<Company>()
    .Where(c => !c.IsDeleted)
    .Select(c => new { c.Description, c.Id }) // <<== Prepare raw data
    .AsEnumerable() // <<== From this point it's LINQ to Object
    .Select(c => new { c.Description, Id = "C"+c.Id }); // <<== Construct end result

尝试使用SqlFunctions.StringConvert Method

var xd = (from c in Repository.Query<Company>()
           where !c.IsDeleted
           select new { c.Description, Id = "C" + SqlFunctions.StringConvert((double)c.Id).Trim()});

您编写的代码可以正常工作。 这是相同代码的模型,它输出Id

class Company
{
    public string Description { get; set; }
    public int Id { get; set; }
    public bool IsDeleted { get; set; }
}

static void Main()
{
    //setup
    var list = new List<Company>();
    list.Add(new Company
    {
        Description = "Test",
        Id = 35,
        IsDeleted = false
    });
    list.Add(new Company
    {
        Description = "Test",
        Id = 52,
        IsDeleted = false
    });
    list.Add(new Company
    {
        Description = "Test",
        Id = 75,
        IsDeleted = true
    });

    /* code you are looking for */
    var providers = from c in list
                    where !c.IsDeleted
                    select new { c.Description, Id = "C" + c.Id };

    foreach (var provider in providers)
    {
        Console.WriteLine(provider.Id);
    }

        Console.ReadKey();
}

字符串格式呢

var providers = from c in Repository.Query<Company>()
                where !c.IsDeleted
                select new { c.Description, Id = "C" + c.Id.ToString() };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM