c# - 使用 .where 和 .select 从列表中的列表中选择单个元素

标签 c# string list ienumerable rectangles

我有一个 List<>类型 world每个世界元素中都有一个 List<>类型 item它本身包含一个 Rectanglestring
这是世界的结构

`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/

相关文章:

c# - 命令行构建解决方案与 Visual Studio 2012 构建

c# - ScaleTransform 部分缩放 ContextMenu

c# - C# WebApi 中的实时 FLV 流式传输

c# - 如何从存储过程中获取 SQL 字符串结果并将其保存在 C# Windows 应用程序字符串变量中

python - 如何在所有 Dictionary.Values() 中搜索字符串中的所有字符

string - Python 硬编码字符串与 str() 方法之间的差异

python - 给定一个字符串,如何返回 json 路径?

string - 使用tr///运算符计算字符串中的字母

c# - List<string> 内存不足异常

delphi - 将对象列表保存在文本文件中