Ram Singh
Ram Singh

Reputation: 6918

replace a word from string in list C# LINQ

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

Please check this for URL format

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

Upvotes: 0

Views: 1845

Answers (2)

Caius Jard
Caius Jard

Reputation: 74605

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

Upvotes: 3

iamdkrz
iamdkrz

Reputation: 21

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

Upvotes: 0

Related Questions