开发者

How to Update an item in a collection using and C#

开发者 https://www.devze.com 2023-04-11 04:32 出处:网络
Some times ago I asked a question here \"How to add an item in a collection using Linq and C#\" For Example I have same collection:

Some times ago I asked a question here "How to add an item in a collection using Linq and C#"

For Example I have same collection:

     开发者_C百科 List<Subscription> subscription = new List<Subscription>
       {
           new Subscription{Type = "Trial", Period = 30 },
           new Subscription{Type = "Free", Period = 90 },
           new Subscription{Type = "Paid", Period = 365 }
       };

Now I want to update an item of this list using C# code. Is it possible?


Your subscription list contains 3 references to 3 Subscription objects. If you update any one of the 3 subscription objects in that list (through whatever means) then the list will reference the updated element.

subscription.First(s => s.Period == 30).Trial = "new";

Will update the subscription object.. List won't change but it references the same object which has been updated


You create a contextmanager for example dbManager

var subscription = dbManager.Subscriptions.Single(s => s.Type == "Free");
subscription.Period = 120;
dbManager.SaveChanges();


To update the first item in your list to a new period you can do this:

subscription[ 0 ].Period = 40;


<_InstanceName>[ItemIndex].<_property>= newValue


Additionally, if you wish to update all items in the collection you could achieve this like so,

subscription.ForEach(s => s.Period = 30);


It should be noted that if Subscription were a value type you'd need to do something like this:

Subscription updateMe = subscription[0];
updateMe.Period = 40;
subscription[0] = updateMe;

I'd also note that collection names are usually plural, so the list should be named subscriptions. I suppose, however, that this convention loses its value if the developers working on the code are native speakers of a language that doesn't use plurals like that.

0

精彩评论

暂无评论...
验证码 换一张
取 消