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

本文关键字:连接 字符串 Int LINQ 查询 | 更新日期: 2023-09-27 18:25:22

我有以下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中做到这一点?

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

尝试使用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()});

当您需要的功能时。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

您编写的代码可以正常工作。这是一个相同代码的模型,它输出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() };