简体   繁体   中英

replace a word from string in list C# LINQ

I have list in which i'm getting URL like:

请检查此 URL 格式

I want to replace "URL//" with actual URL like any URL. why i'm doing this, because, the URL will be dependent on environment website is being accessed for. like for stage, it will use stage's url and so on.

I have tried:

ProductReviews.Items.ToList().ForEach(x => x.AvatarUrl.Replace("URL", serverImageUrl));

but as per my understanding it requires full string value as "URL". Please help me

You don't use LINQ to perform modifications to your data collection. If you want to modify the collection, use a normal foreach loop

foreach(var pr in ProductReviews)
  pr.AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl);

Remember: "LINQ is for querying, not modifying"

If you want to replace URL using LINQ you do it as part of a query that returns a enumeration of new objects that represent your replacements:

ProductReviews.Select(pr => new { Review = pr, ReplacedUrl = pr.AvatarUrl.Replace("URL", serverImageUrl) } );

This will give you an enumerable of new objects that has the original and the replaced url. It's easier to include the original, assuming you need all the fields, as a single field but you could also list out the things you want:

ProductReviews.Select(pr => new {
   pr.Id, 
   pr.CustomerId,
   AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl)
} );

Or you can use an automapper to map your db objects to your client side objects and save a bit of this laborious typing

ProductReviews.Items.ToList().ForEach(x => x.AvatarUrl = x.AvatarUrl.Replace("URL", serverImageUrl));

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