-1

To make my long story short i had to improvise this code a little:

public class Faerie
{
    public string Name;
}

public class Example
{
    List<Faerie> faeries = new List<Faerie>() { 
        new Faerie { Name = "Wild Faerie" } ,
    new Faerie { Name = "Smoke Faerie" },
    new Faerie { Name = "Red Faerie" }
    };

    string[] faerieNamesFromInput = new string[] { "White Faerie", "Wild Faerie", "Dark Faerie" };

    public Faerie ReturnMatchedFromInput()
    {

    }
}

How can i return a Fairy object from the fairies list if its name matches a name from the user input? Like for instance, here i want to return the Faerie with name Wild Faerie because it's name matches.Is there a short LINQ way for that or i have to go with for loop?

Mama Tate
  • 273
  • 5
  • 12
  • 1
    What have you tried? This is a pretty basic `Where`/`FirstOrDefault` query. – vgru Aug 30 '14 at 07:58
  • This is pretty basic, but to be honest this is the second time that i want to use LINQ because i don't use it designing my simple games and my knowledge of it is at beginners level – Mama Tate Aug 30 '14 at 08:00
  • @Groo it's only simple if you know the answer. – James Aug 30 '14 at 08:03
  • 1
    @James: Sure, but googling is also pretty simple. This question has been asked and answered dozens of times. *That's* whats simple. Hence the "what have you tried" question. The number of different threads I get by googling for "linq find item from another list" or "linq find string in list" is ridiculous. – vgru Aug 30 '14 at 08:13

2 Answers2

2

If you want to return multiple matches

faeries.Where(x => faerieNamesFromInput.Contains(x.Name));

If you want to return the first matched then

faeries.FirstOrDefault(x => faerieNamesFromInput.Contains(x.Name));
James
  • 80,725
  • 18
  • 167
  • 237
0

Simply do

var result = faeries.FirstOrDefault(x => faerieNamesFromInput.Contains(x.Name));

Make sure to include System.LINQ namespace.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208