query a list of dynamic objects for a FirstOrDefault

随声附和 提交于 2019-12-08 09:59:02

问题


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


来源:https://stackoverflow.com/questions/8978619/query-a-list-of-dynamic-objects-for-a-firstordefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!