1

I wrote some code with foreach loop but it looks very ugly and I wanna translate it into LINQ version but i can't figure out how to do that (sorry, I am new to LINQ) and can someone tell me the LINQ way of my code which is given below?

        GameObject[] everything = Resources.FindObjectsOfTypeAll(
                                 typeof(GameObject)) as GameObject[];
        GameObject layoutContainer = new GameObject();

        foreach (GameObject obj in everything) {
            if(obj.name == "LayoutContainer") {
                layoutContainer = obj;
                break;
            }
        }
2
  • 2
    You looking for FirstOrDefault method. Something like layoutContainer = everything.FirstOrDefault(obj => obj.name == "LayoutContainer") Commented Jul 16, 2019 at 13:20
  • Thanks for your response, it worked Commented Jul 16, 2019 at 13:26

3 Answers 3

3

You can convert this to LINQ with the following code:

GameObject layoutContainer = everything.FirstOrDefault(obj => obj.name == "LayoutContainer") ?? new GameObject();

This grabs the first object with the name of "LayoutContainer". If there is no object with that name, it will assign it a new object. This is the same functionality that you have shown in your code example.

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

3 Comments

Thanks for your answer. I have already tried this but in FirstOrDefault method i was using { } this action qurly braces and compiler was saying that "not all code path returns a value", now i understand, i just had to pass logic as parameter and not as an action
Your error came from the scoping curly braces. Leave those out and use the code as I wrote it and you should be all set.
Yes, I did that and now all is fine
2
GameObject layoutContainer = (from game in everything
                                          where game.name == "LayoutContainer"
                                          select game).FirstOrDefault();

Comments

1

Try this:

GameObject layoutContainer = (Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[])?
   .FirstOrDefault(x => x.name == "LayoutContainer") ?? new GameObject();

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.