How do I combine these similar linq queries into one?

Posted by MikeD on Stack Overflow See other posts from Stack Overflow or by MikeD
Published on 2010-05-04T15:19:59Z Indexed on 2010/05/04 15:28 UTC
Read the original article Hit count: 243

Filed under:
|

This is probably a basic LINQ question. I have need to select one object and if it is null select another. I'm using linq to objects in the following way, that I know can be done quicker, better, cleaner...

    public Attrib DetermineAttribution(Data data)
    {

        var one = from c in data.actions
                           where c.actionType == Action.ActionTypeOne
                           select new Attrib 
                                      {
                                          id = c.id,
                                          name = c.name
                                      };
        if( one.Count() > 0)
            return one.First();

        var two = from c in data.actions
                  where c.actionType == Action.ActionTypeTwo
                  select new Attrib
                             {
                                 id = c.id,
                                 name = c.name
                             };
        if (two.Count() > 0 )
            return two.First();

  }

The two linq operations differ only on the where clause and I know there is a way to combine them. Any thoughts would be appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ