0

Question on searching for records in nested classes. Here's a cut down version of my code. Hopefully it explains enough! I'm using Visual Web Developer 2010 Express.

Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace API
{
    public class Fixture
    {
        public int ID { get; set; }
        public string Description { get; set; }
        public List<FixturesMarketData> FixturesMarketData;

        public Fixture()
        {
            FixturesMarketData = new List<FixturesMarketData>();
        }

        public void AddMarket(int _fixtureID, int _marketID, string _MarketName)
        {
            FixturesMarketData.Add(new FixturesMarketData ( _fixtureID, _marketID, _MarketName ));
        }

        public string ListMarkets()
        {
            string strReturn="";
            foreach (var item in FixturesMarketData)
             {
                strReturn = strReturn + "<br />" + item.marketDescription + " - " + item.marketID + " - " + item.fixtureID;
            }
            return strReturn;
        }
    }

    public class FixturesMarketData
    {
        public int fixtureID { get; set; }
        public int marketID { get; set; }
        public string marketDescription { get; set; }

        public FixturesMarketData(int _mdfixtureID, int _mdmarketID, string _mdmarketDescription)
        {
            fixtureID = _mdfixtureID;
            marketID = _mdmarketID;
            marketDescription = _mdmarketDescription;
        }
    }
}

Main Code

_fixtures = new List<Fixture>();
_fixtures.Add(new Fixture { ID = 1234, Description = 'This is a test' });

int index = _fixtures.FindIndex(Fixture => Fixture.ID.Equals(1234));
_fixtures[index].AddMarket(1234, 5678, 'This is a test market');
AddToOutputString(_fixtures[index].ListMarkets());

So basically this would result in: Fixture:

ID= 1234;
Description=This is a test;
FixturesMarketData
FixtureID=1234;
MarketID=5678;
marketDescription=This is a test market;

How do I do a find on FixturesMarketData for where market id equals 5678?

I can do it like this:

var index=-1;
            foreach (var item in _fixtures)
            {
                index = item.FixturesMarketData.FindIndex(entry => entry.marketID.Equals(_marketId));
                if(index!=-1)
                {
                    break;
                }
            }

but I'm guessing there must be a way to do it in Lambda Find style

Thanks!

Richard Whitehouse
  • 679
  • 3
  • 14
  • 28

1 Answers1

1
var enumerable=_fixtures.Where(x=>x.FixturesMarketData.Any(x=>x.marketId==5678));

now if you hope to find many such fixtures you can do

enumerable.ToList();

if you want only the first one then

enumerable.FirstOrDefault();

and if only one fixture can be found then

enumerable.SingleOrDefault();

Note: Here Default means if not found return NULL else there will be an error thrown

Baz1nga
  • 15,485
  • 3
  • 35
  • 61