我有一个 List<>
类型 world
每个世界元素中都有一个 List<>
类型 item
它本身包含一个 Rectangle
和 string
这是世界的结构
`class world
public Items[] items { get; set; }
public world(int nooflevels, int noofitems)
{
//when creating a world make the items
items = new Items[noofitems];
for (int i = 0; i < noofitems; i++)
{
items[i] = new Items();
}
}
}`
和项目
class Items
{
public new Rectangle spriterect;
public string type { get; set; }
public Items()
{
spriterect.X = 0;
spriterect.Y = 0;
spriterect.Width = 0;
spriterect.Height = 0;
type = "default";
}
}
这个世界列表是这样创建的
List<world> Worlds = new List<world>();
我试图根据类型从项目列表中取出一个特定的矩形
void getitem(string thetype, int world)
{
Rectangle a = Worlds[world].
items.Where(f=> f.type == thetype).
Select(g => g.spriterect);
}
所以我希望这会选择包含 .type thetype 的 item[].spriterect
我希望它返回该项目中的矩形,但它返回一个 IEnumerable
我如何让它根据类型返回单个矩形?
最佳答案
您应该从项目中选择单个项目。如果应该有指定类型的单个矩形,则使用 SingleOrDefault
:
var item = Worlds[world].items.SingleOrDefault(i => i.type == thetype);
if (item != null)
a = item.spriterect;
如果您完全确定始终存在指定类型的矩形,则只需使用
Single
:Rectangle a = Worlds[world].items.Single(i => i.type == thetype).spriterect;
关于c# - 使用 .where 和 .select 从列表中的列表中选择单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863601/