查询动态对象的列表为一个FirstOrDefault [英] query a list of dynamic objects for a FirstOrDefault
问题描述
下面code将返回一个可枚举动态对象。
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引用转换)并粘贴到程序。 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!