简体   繁体   English

如何在List中串联两个列值?

[英]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 . 我试图将一个列表中的两个列值连接起来并分别选择所有列,但我能实现的是在列表中获取一个没有其他现有列数据的连接列。由于我正在使用select所以我松散了列表中的其他列数据连接。

Linq Query: Linq查询:

 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 . 我需要修改数据,例如列名Name将保留Id+Place并且所有列数据( PlaceAddress等)都可以保持不变。

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. 尽管您不需要“包括” m.Place,m.Address等名称(Visual Studio会根据属性名称对它们进行适当的命名),但我发现如果保留该名称,将更容易阅读语法一致。

Assuming you want to update specific fields you could use the foreach clause. 假设您要更新特定字段,可以使用foreach子句。 This will update the values in place without needing to call ToList as well. 这将在适当的位置更新值,而无需调用ToList。

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

Use select new : 使用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). 用您的类名( 与该类是数据的集合是同一类,或者使用这些属性名来更新DTO / View模型)来更新Category

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

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