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 .
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.
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);
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)});
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.