Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq lambda foreach

Tags:

c#

lambda

linq

Trying for wrap each string in array but it doesn't works, means foreach loop, please explain why

string s = "keepsakes,table runners,outdoor accessories";
List<string> keys = s.Split(',').ToList();
keys.ForEach(x => x = String.Concat("%", x, "%"));
s = String.Join(",", keys);
Console.WriteLine(s); 

need to get "%keepsakes%,%table runners%,%outdoor accessories%"

UPD: Thanks a lot for suggestions(it's a same way)

but some one can answer why this is works and not works under:

object

    public class MyItems
    {
        public string Item { get; set; }
    }

and func

        string s = "keepsakes,table runners,outdoor accessories";
        List<MyItems> keys = s.Split(',').ToList().Select(x => new MyItems(){ Item = x }).ToList();
        keys.ForEach(x => x.Item = String.Concat("%", x.Item, "%"));
        s = String.Join(",", keys.Select(x => x.Item).ToList());
        Console.WriteLine(s);
like image 898
AleksP Avatar asked Nov 28 '22 07:11

AleksP


1 Answers

You are not modifying the list within the ForEach, you are just creating strings that are assigned to the local variable x but then thrown away. You could use a for-loop:

for(int i = 0; i < keys.Count; i++)
{
    keys[i] = String.Concat("%", keys[i], "%");
}

For what it's worth, here the shorter LINQ version which also circumvents the core issue:

s = string.Join(",", s.Split(',').Select(str => "%" + str + "%"));
like image 151
Tim Schmelter Avatar answered Dec 12 '22 21:12

Tim Schmelter