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!
now if you hope to find many such fixtures you can do
if you want only the first one then
and if only one fixture can be found then
Note: Here Default means if not found return
NULLelse there will be an error thrown