ChrisLively
ChrisLively

Reputation: 88044

Linq to Objects where clause and typecasting

I have the following:

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"});

Now, what I want to do is pull out the DisplayName of the specific option that matches StoredValue.

Previously, I'd iterate over the entire collection until I found a match. But, I'd rather have something that looked a bit better...

I got started with

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

And that's where I'm stuck.

Upvotes: 1

Views: 1672

Answers (4)

David
David

Reputation: 3804

This should do it:

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

Upvotes: 2

the_joric
the_joric

Reputation: 12226

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

Upvotes: 2

CrazyDart
CrazyDart

Reputation: 3801

This is using Linqpad. You need to cast as the Option type first, then you can use it. I put in a check to find all of that type then check for the value.

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>(); }
}

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

I think this is what you want: (Single will error if 0 or more than 1 match is found)

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

Or to allow for multiple values: (this will give you all the display names that match, 0 to many)

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

Upvotes: 3

Related Questions