简体   繁体   English

通用列表修改C#中的属性值

[英]Generic list modify value of property in C#

Lets say i have following class 可以说我有以下课程

public class abc
{
    int id;
    string name;
}

i am using this class as a collection of some data and my business logic appends some rows in it. 我正在使用此类作为一些数据的集合,而我的业务逻辑在其中添加了一些行。

List<abc> lstData = GetData();

Now if i have to modify some property value lets say i want to modify the name property with some value. 现在,如果我必须修改某些属性值,可以说我想用某些值来修改name属性。

string replaceName = 'jay';

so this jay should be in every row of the list in name property. 所以这个杰伊应该在name属性的列表的每一行中。

how to do this ? 这个怎么做 ? i think there is a convertAll method can we use that.... 我认为有一个convertAll方法可以使用吗....

ConvertAll is usually used to create a new list , whereas it sounds like you just want to modify properties within existing objects. ConvertAll通常用于创建新列表 ,而听起来就像您只想修改现有对象中的属性。 So I'd use: 所以我会用:

foreach (abc value in lstData)
{
    value.name = replaceName;
}

(This code would look more idiomatic if you'd used names following the .NET naming conventions , by the way.) (顺便说一下,如果您使用遵循.NET命名约定的名称,则此代码看起来会更加惯用。)

Alternatively, you could use ConvertAll if you wanted to create new objects: 另外,如果要创建对象,可以使用ConvertAll

List<abc> newList = lstData.ConvertAll(old => new abc { 
    id = old.id,
    name = replaceName
});

That's using a lambda expression for the delegate, and an object initializer to set the properties in each new object. 这使用了一个lambda表达式作为委托,并使用一个对象初始化程序来设置每个新对象的属性。 The exact way that you'd approach this would depend on your real class. 具体的处理方式取决于您的实际课堂。

使用List.ForEach

lstData.ForEach(x => x.name = "jay");

您可以使用下面的LINQ运算符ForEach():

lstData.ForEach(data => data.Name = replaceName);

Do you mean you want to assign the same value to a property of all the object in the list? 您是否要为列表中所有对象的属性分配相同的值? If yes then you loop over it: 如果是,则循环遍历:

foreach (var item in lstData)
{
    item.name = "jay";
}

I think in real life, when you want to modify Name , you must be having Id, so based on that you can find a single object to be modified in the list like: 我认为在现实生活中,当您想要修改Name ,您必须具有Id,因此可以在列表中找到一个要修改的对象,例如:

 abc objAbc =(
    from emp 
    in lstData 
    where emp => emp.Id = someId 
    select emp)
    .SingleOrDefault(); 

Once you have objAbc you can do objAbc.Name = "New Name" 拥有objAbc you can do objAbc.Name = "New Name"

I hope that's what you want to know. you need to do using System.Linq I hope that's what you want to know. you need to do using System.Linq in order to use linq-to-object. I hope that's what you want to know. you need to do using System.Linq才能使用linq-to-object。

Happy coding 快乐编码

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

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