8

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;
    – Rob
    Dec 30, 2015 at 15:44
  • both the class and the prop are public. Still getting the error, is my linq correct?
    – Chris
    Dec 30, 2015 at 15:47

3 Answers 3

18

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();
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
  • both the class and the prop are public. Still getting the error, is my linq correct?
    – Chris
    Dec 30, 2015 at 15:47
  • @Chris What error does it produce now? I think you should change your doritos too
    – Ian
    Dec 30, 2015 at 15:48
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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.