super cool
super cool

Reputation: 6045

How to concatenate two column values inside List?

I'm trying to concatenate two column values inside a list and respectively select all columns but all I can achieve is get a concatenated column inside list with no other existing columns data .As I loose other columns data inside list because I'm using select to concatenate .

Linq Query:

 data = data.Select(m => m.Name = m.Id + m.Place).ToList(); // m=>m kindoff with concatenation 

I need data to be modified like column name Name will hold Id+Place and I get all columns data intact (Place,Address,etc) can be many more .

Upvotes: 0

Views: 4934

Answers (4)

CodeHxr
CodeHxr

Reputation: 885

Try something like this...

data = data.Select(m => new
{
    Name = $"{m.Id} {m.Place}", // Edit to add string interpolation
    Place = m.Place,
    Address = m.Address,
    etc = m.etc
});

While you don't "need" to include a name for m.Place, m.Address, etc. (Visual Studio will name them appropriately based off the of the property name), I find that it's easier to read if you keep the syntax consistent.

Upvotes: 3

Salah Akbari
Salah Akbari

Reputation: 39956

Use select new:

var data2 = from c in data
            select new
            {
                Name = c.Id + " " + c.Place,
                Place = c.Place,
                Address = c.Address
            };

Or:

var data3 = data.Select(c => new { c.Address, Name = string.Format("{0} {1}", c.Id, c.Place)});

Upvotes: 0

momar
momar

Reputation: 364

Assuming you want to update specific fields you could use the foreach clause. This will update the values in place without needing to call ToList as well.

data.ForEach(m => m.Name = m.Id + m.Place);

Upvotes: 1

Shyju
Shyju

Reputation: 218732

There are already two answers which should work for you. But they give you a list of anonymous objects.

The below will give a list of your custom class(instead of anonymous object) with the desired result.

var result = data.Select(m => new Category 
                                { Name = m.Name = m.Id + m.Place,
                                  Place = m.Place} ).ToList();

Update Category with your class name (the same class which data is a collection of or a different DTO/View model with those property names).

Upvotes: 0

Related Questions