Foreach IEnumerable reference by string

时间:2016-06-14 18:28:02

标签: c# asp.net-mvc linq

I am trying to access the contents of an IEnumerable by string rather than int.

METHOD

public List<Foo> GetFoo(IEnumerable<Bar> bar)
{
    List<Foo> foo = new List<Foo>();

    var query = from x in bar       
                select new Foo()
                {
                    foo = x.foo,
                    bar = x.bar
                };
    foo = query.ToList();
    return foo;
}

VIEW

<td>@foo["bar"].foo<td>

I know the above doesn't exist, but that's what i'm looking to do. If i do foo[0].foo it --obviously-- works.

EDIT

I went with the Dictionary<string,Foo> approach as @D Stanley and @juharr recommended, but i still have to iterate through these results via a foreach loop in order to access the KeyValuePair. I'm trying to bypass a foreach and access the results just via the Key. Is this possible?

public Dictionary<string,Foo> GetFoo(IEnumerable<Bar> bar)
{
    var query = from x in bar               
                select new Foo()
                {
                    foo = x.foo,
                    bar = x.bar
                };
    return query.ToDictionary(f=>f.foo,f=>f);            
}

2 个答案:

答案 0 :(得分:1)

List结构没有任何紧凑的东西。它只有一个接受整数的索引器(你想要的项目的索引)。一些选择:

  • 子类型List<Foo>,用于添加接受字符串的索引器
  • 使用字典而不是List<Foo>

    public Dictionary<string,Foo> GetFoo(IEnumerable<Bar> bar)
    {
        var query = from x in bar       
                    select new Foo()
                    {
                        x.foo,
                        x.bar
                    };
    
        return query.ToDictionary(f => f.bar, f => f));
    }
    

然后foo["bar"]将为Foo提供由"bar"索引的{{1}}对象。您不需要迭代整个集合来查找具有匹配键的对象。

答案 1 :(得分:0)

通过更多挖掘,我能够通过C# List of objects, how do I get the sum of a property

找到答案

使用上面的示例,我使用linq实现了以下逻辑:

方式

public List<Foo> GetFoo(IEnumerable<Bar> bar)
{
    List<Foo> foo = new List<Foo>();

    var query = from x in bar       
                select new Foo()
                {
                    name= x.name,
                    amount = x.amount
                };
    foo = query.ToList();
    return foo;
}

查看

@double total = foo.Where(item => item.name == "jon").Sum(item => item.amount);    
<td>@total<td>

在我看来,我会用变量替换“jon”以减轻foreach中的foreach。对不起所有的困惑,但感谢大家的帮助!!