Linq to Objects where子句和类型转换

时间:2012-03-15 22:33:35

标签: c# linq-to-objects

我有以下内容:

class BaseType {
  public Int32 Id { get; set; }
}

class Option : BaseType {
  public String DisplayName { get; set; }
  public String StoredValue { get; set; }
}

class Container {
  public Collection<BaseType> Options;
}


Container c = new Container();
c.Options.add(new Option() { Id=1, DisplayName="Bob", StoredValue="aaaa"});
c.Options.add(new Option() { Id=2, DisplayName="Dora", StoredValue="bbbb"});
c.Options.add(new Option() { Id=3, DisplayName="Sara", StoredValue="cccc"});

现在,我想要做的是拉出与StoredValue匹配的特定选项的DisplayName。

以前,我会迭代整个集合,直到找到匹配项。但是,我宁愿有一些看起来更好的东西......

我开始使用

var found = (from c in c.Options
             where ...

这就是我被困住的地方。

4 个答案:

答案 0 :(得分:3)

我认为这就是你想要的:( Single如果找到0或超过1匹配就会出错)

string searchValue = "aaaa";
string displayName = c.Options.OfType<Option>.Single(o => o.StoredValue == searchValue).DisplayName;

或者允许多个值:(这将为您提供匹配的所有显示名称,0到多个)

IEnumerable<string> displayNames = from o in c.Options.OfType<Option>
                                   where o.StoredValue == searchValue
                                   select o.DisplayName;

答案 1 :(得分:2)

这应该这样做:

c.Options.OfType<Option>()
 .Where(o => o.StoredValue == "aaaa")
 .Select(o => o.DisplayName)
 .SingleOrDefault();  //or .ToList() 

答案 2 :(得分:2)

var found = (from c in c.Options.OfType<Option>()
             where c.StoredValue == yourValue
             select c.DisplayName).FirstOrDefault();

答案 3 :(得分:1)

这是使用Linqpad。您需要首先转换为Option类型,然后才能使用它。我检查了所有类型然后检查值。

void Main()
{
    Container c = new Container();
    c.Options.Add(new Option() { Id=1, DisplayName="Bob", StoredValue="aaaa"});
    c.Options.Add(new Option() { Id=2, DisplayName="Dora", StoredValue="bbbb"});
    c.Options.Add(new Option() { Id=3, DisplayName="Sara", StoredValue="cccc"});

var t = from x in c.Options.OfType<Option>()
        where x.DisplayName == "Bob"
        select x.StoredValue;
t.Dump();

}

class BaseType {
  public Int32 Id { get; set; }
}

class Option : BaseType {
  public String DisplayName { get; set; }
  public String StoredValue { get; set; }
}

class Container {
  public List<BaseType> Options;

  public Container() { Options = new List<BaseType>(); }
}