在嵌套类中搜索记录的问题。这是我的代码的缩减版本。希望它足够解释!我正在使用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风格中实现它
谢谢!
答案 0 :(得分:1)
var enumerable=_fixtures.Where(x=>x.FixturesMarketData.Any(x=>x.marketId==5678));
现在如果你希望找到很多这样的灯具你可以做到
enumerable.ToList();
如果你只想要第一个
enumerable.FirstOrDefault();
如果只能找到一个灯具那么
enumerable.SingleOrDefault();
注意:这里默认表示如果找不到则返回NULL
否则会抛出错误