query a list of dynamic objects for a FirstOrDefau

2019-06-13 12:49发布

问题:

The following code will return an Enumerable of dynamic objects.

protected override dynamic Get(int id)
{ 
    Func<dynamic, bool> check = x => x.ID == id;
    return  Enumerable.Where<dynamic>(this.Get(), check);
}

How do I select the FirstOrDefault so it is a single object not an Enumerable?

Similar to this answer but just want SingleOrDefault.

回答1:

Simplest way is probably

protected override dynamic Get(int id)
{ 
    return Get().FirstOrDefault(x=>x.ID==id);
}

Since some people have had trouble making this work, to test just do a new .NET 4.0 Console project (if you convert from a 3.5 you need to add System.Core and Microsoft.CSharp references) and paste this into Program.cs. Compiles and runs without a problem on 3 machines I've tested on.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;

namespace ConsoleApplication1
{
    internal class Program
    {
        protected dynamic Get2(int id)
        {
            Func<dynamic, bool> check = x => x.ID == id;
            return Enumerable.FirstOrDefault<dynamic>(this.Get(), check);
        }

        protected dynamic Get(int id)
        {
            return Get().FirstOrDefault(x => x.ID == id);
        }

        internal IEnumerable<dynamic> Get()
        {
            dynamic a = new ExpandoObject(); a.ID = 1;
            dynamic b = new ExpandoObject(); b.ID = 2;
            dynamic c = new ExpandoObject(); c.ID = 3;
            return new[] { a, b, c };
        }

        static void Main(string[] args)
        {
            var program = new Program();
            Console.WriteLine(program.Get(2).ID);
            Console.WriteLine(program.Get2(2).ID);
        }

    }

}


回答2:

You could use your code with FirstOrDefault instead of Where. Like this:

protected override dynamic Get(int id)
{ 
    Func<dynamic, bool> check = x => x.ID == id;
    return Enumerable.FirstOrDefault<dynamic>(this.Get(), check);
}


回答3:

Just so?

protected override dynamic Get(int id)
{ 
    Func<dynamic, bool> check = x => x.ID == id;
    return Enumerable.Where<dynamic>(this.Get(), check).FirstOrDefault();
}