0

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

2
  • 1
    Just wondering... why do you want to use LINQ? Not sure if LINQ fits into the stack that you are using in that particular example you're providing. Commented Apr 30, 2013 at 1:47
  • Read this: blogs.msdn.com/b/ericlippert/archive/2009/05/18/… Commented Apr 30, 2013 at 3:27

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

May provide quicker lookup times (see dotnetperls.com/dictionary-time).
0

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++;
                        });

Comments

0
someActions.Intersect(contains).ForEach(callRoutine);

OR

someActions.Intersect(contains).ForEach(i=>callRoutine(i));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.