关于在嵌套类中搜索记录的问题。这是我的代码的精简版。希望它解释得足够多!我正在使用 Visual Web Developer 2010 Express。
班级
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;
}
}
}
主要代码
_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());
所以基本上这会导致:
ID= 1234;
Description=This is a test;
FixturesMarketData
FixtureID=1234;
MarketID=5678;
marketDescription=This is a test market;
如何在 FixturesMarketData 上查找市场 id 等于 5678 的位置?
我可以这样做:
var index=-1;
foreach (var item in _fixtures)
{
index = item.FixturesMarketData.FindIndex(entry => entry.marketID.Equals(_marketId));
if(index!=-1)
{
break;
}
}
但我猜肯定有办法以 Lambda Find 风格做到这一点
谢谢!