Jonathan Wood
Jonathan Wood

Reputation: 67193

Concatenate Int to String in LINQ Query

I have the following LINQ query.

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

I'm trying to concatenate the ID to "C". So, for example, if c.Id is 35 then the result should be "C35".

This obviously doesn't work because you can't add an integer (c.Id) to a string. I could easily resolve this in C# using string.Format() or converting the type. But how can I do this in LINQ?

Upvotes: 0

Views: 1315

Answers (4)

Matt Rowland
Matt Rowland

Reputation: 4595

The code that you have written will work fine. Here is a mock up of the same code and it outputs the Id's

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();
}

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39956

Try using 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()});

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

When you need functionality of .NET only in preparing the result (as opposed to, say, filtering, which should be done on RDBMS side to avoid bringing too much data in memory) the common trick is to complete the conversion in memory using the AsEnumerable method:

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

Upvotes: 2

Ro.
Ro.

Reputation: 1753

What about string format

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

Upvotes: 0

Related Questions