Reputation: 1561
I currently have some code that looks like this
string[] contains = new string[]{"marge", "homer", "lisa", "bart", "maggie"};
string[] actions = new string[]{"get dye", "mmm beer", "blow saxophone", "have a cow", "bang"};
for (int i = 0; i < someActions.Count; ++i)
{
if (someActions.Contains(contains[i]))
callRoutine(actions[i]);
}
(this is a very trivial example - someActions is a List)
I'm wondering if there is a way in LINQ to do the same as loop? I'm thinking of something along the lines of
int i = position in contains or 0
callRoutine(actions[i]);
The problem is that I don't know how to use an array as the search parameter. Various searches suggest I need to use IEnumerable to do this, but I'm not sure.
Any help would be appreciated here.
Paul
Upvotes: 0
Views: 75
Reputation: 13399
someActions.Intersect(contains).ForEach(callRoutine);
OR
someActions.Intersect(contains).ForEach(i=>callRoutine(i));
Upvotes: 0
Reputation: 707
This wouldn't work nicely with your current data setup.
If you are flexible on your data, you could try this:
var namesToActions = new Dictionary<string, string>()
{
{ "marge" , "get dye" },
{ "homer", "mmm beer"},
{ "lisa", "blow saxophone"},
{ "bart", "have a cow"},
{ "maggie", "bang"}
};
someActions.ForEach(a => callRoutine(namesToActions[a]));
Switching to a Dictionary makes it a little easier to perform the type of Linq action you're looking for and provides additional flexibility and quicker lookup times.
Upvotes: 1
Reputation: 1483
I'm not sure what your purpose is, but if you want to convert your for loop into a linq statement, you can do this:
var i = 0;
someActions.ForEach(x =>
{
if (someActions.Contains(contains[i]))
callRoutine(actions[i]);
i++;
});
Upvotes: 0