9

I have a list of foo called crepes. I want to return foo where bar.doritos == "coolRanch"

class foo
{
    List<bar> item;
    string candy;
    string beer;
}

class bar
{
    string doritos;
    string usb;
}

var item = crepes.item.Where(x => x.doritos == "coolRanch").FirstOrDefault();

From other threads, i've pieced together the above linq query, but crepes.item throws an error. "List does not contain a definition for 'item' and no definition for 'item' accepting first argument...

2
  • 1
    Fields in C# are private by default. Change your declaration to public List<bar> item; Commented Dec 30, 2015 at 15:44
  • both the class and the prop are public. Still getting the error, is my linq correct? Commented Dec 30, 2015 at 15:47

3 Answers 3

20

Given that crepes is a List<Foo>, you need to add an additional level to the linq query.

var item = crepes.Where(a => a.item.Any(x => x.doritos == "coolRanch")).FirstOrDefault();
Sign up to request clarification or add additional context in comments.

Comments

3

Your item access modifier is private (this is C# default for class), it should be made public

This goes for your doritos too

Also, since your crepes is a List, put additional layer of LINQ (as also suggested by others) to completely fix it, something like this

var item = crepes.Where(f => f.item.Any(b => b.doritos == "coolRanch")).FirstOrDefault(); //f is of foo type, b is of bar type

2 Comments

both the class and the prop are public. Still getting the error, is my linq correct?
@Chris What error does it produce now? I think you should change your doritos too
2

If you fix your classes like this

class Foo
{
    public List<Bar> Items { get; set; }
    public string Candy { get; set; }
    public string Beer { get; set; }
}

class Bar
{
    public string Doritos { get; set; }
    public string Usb { get; set; }
}

Your query will look like

var crepes = new List<Foo>();
var item = crepes.FirstOrDefault(f => f.Items.Any(b => b.Doritos == "coolRanch"));

Here, we are trying to get the first Foo which has at least one Bar in Items where Doritos == "coolRanch".

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.