English 中文(简体)
避免切换大小写 -linq [重复]
原标题:Avoid switch case -linq [duplicate]
  • 时间:2012-05-22 12:28:43
  •  标签:
  • c#
  • .net
  • linq
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Dynamic LINQ OrderBy

  switch (sort) {
                case "Title":
                    queryResults = queryResults.OrderBy(r => r.Title);
                    break;
                default:
                    queryResults = queryResults.OrderBy(r => r.LastName);
                    break;

我能摆脱上面的开关区吗?

我可以做一些事情,比如:

queryResults = queryResults.OrderBy(r => r."sort");
or
queryResults = queryResults.OrderBy(r => r.sort);
最佳回答

如果您想要完全动态地进行, 您可以使用一些反射( 简单的示例) :

string prop = "Title";
var q = queryResults.OrderBy(x => x.GetType().GetProperty(prop).GetValue(x, null));

我无论如何都不会认为这是最好的解决方案。这是否真正有意义取决于你从何处获得财产名称(如果你从反省得到,是否也得到),以及有多少属性。

问题回答

这样应该可以了

queryResults = queryResults.OrderBy(r => sort == "Title" ? r.Title : r.LastName)

http://weblogs.asp.net/scottgu/archive/2008/01/07/hird-linq-part-1-useing-the-linq-hild-query-library.aspx" rel=“nofollow”>DynamcLinq 。我一年多来没有碰过它,但我有预期的结果。您的代码会改为:

queryResults = 查询Results. OrderBy (sort); = 查询Results. OrderBy(sort);

哦,酷,它也是"https://nuget.org/packages/DynamicLINQ" rel="nofollow">NuGet软件包也





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签