本文介绍了查询FirstOrDefault的动态对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将返回Enumerable的动态对象。

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

如何选择 FirstOrDefault 单个对象不是枚举?

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

类似于,但只是想要SingleOrDefault。

Similar to this answer but just want SingleOrDefault.

推荐答案

最简单的方法可能是

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

由于有些人在做这项工作时遇到麻烦,要测试一下新的.NET 4.0控制台项目(如果您从3.5转换需要添加System.Core和Microsoft.CSharp引用)并将其粘贴到Program.cs中。在我测试的3台机器上编译并运行没有问题。

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

    }

}

这篇关于查询FirstOrDefault的动态对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:53