Madam Zu Zu
Madam Zu Zu

Reputation: 6605

LINQ - Convert to String LIST and Replace Characters

I have a dataset that is returned from a stored procedure that I save into a string LIST.

So far this is what I have and it's working correctly:

 this.UserOrgs = ds.Tables[0].AsEnumerable()
           .Select(r => r.Field<string>(0))
                            .ToList();

However, I also need to replace all "X" with "Y" in the returned values before I put them into the list.

I guess my question is, can I do it all at one time using LINQ? Or should I replace the characters in the dataset before I convert it into a list?

Upvotes: 2

Views: 1392

Answers (2)

SoftwareSprint
SoftwareSprint

Reputation: 21

var chars = new[] { "X", "Y" };
EnumerableRowCollection<string> enumerableRowCollection = dataTable.AsEnumerable().Select(r => chars.Aggregate(r.Field<string>(0), (s, s1) => s.Replace(s1, string.Empty)));

The above answer will replace all X's and all Y's.

At least anything that you put in the char array

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500275

Sure, it's easy to do this - you don't even need another call:

this.UserOrgs = ds.Tables[0].AsEnumerable()
                            .Select(r => r.Field<string>(0).Replace("X", "Y"))
                            .ToList();

Upvotes: 6

Related Questions