简体   繁体   中英

How to update a element in List collection in C#

I have a List collection like List<clsTest> objList = new List<clsTest>();

It has around hundred columns.

Predicate<ScreenDefinition> linqQuery = new Predicate<ScreenDefinition>(objQuery);
index = tmp.FindIndex(objQuery);

objQuery is query for conditions

I tried like for update

listJoinedScreenDefinition[index].fieldName = "update";

But prob is i need to genrate 'fieldName' dynamically according to my logic.

Say "seat" + 05 => seat05 is the column name.

Like wise seat1 - seat 100 are there.

In every iteration i need to update only one column.

in the way i tried how to pass the dynamically column name in that List ?

I am new to .Net and Linq.

Please suggest some way to achieve this..

Your question has nothing to do with lists and queries. You would be in the same situation if you had only one instance of your clsTest class. The problem is with the design of the class.

If I understand you correctly, clsTest has 100 members, with names like seat1 , seat2 , seat50 , etc, is that correct? If so, that's a pretty bad class design, as you've found out, because it requires you to hardcode all references to specific fields inn your code, or alternately use reflection (as Garath suggested in his answer) which is is more complicated and error prone.

A better solution would be to redesign your clsTest class to have a property called Seats which is an Array or List of seats. If you have a public List<string> Seats {get;set;} , you can access myObject.Seats[5] to get to the fifth seat.

Of course, if it's more than just a list of seats, and you can have several different types of numbered properties ("seat" + "05" and "row" + "02", for instance), you can use a Dictionary<string, string> , to map between "seat05" and its value.

The easiest way is to using reflection. I do not know if you are using properties or fields. For properties code will look like:

var target = listJoinedScreenDefinition[index];
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);

For fields code is very similar:

var target = listJoinedScreenDefinition[index];
FieldInfo fi = target.GetType().GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(target ,value)

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.

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