English 中文(简体)
具有无价值的实体应在按批次按顺序分类后成为最后实体。
原标题:entity that has null value should be last entity after sorting by using order by in c#

我有一份清单,我想用林克(按方法顺序排列)来分类。 我名单上的一些实体对“孤儿”财产没有价值,我想按这一规则分类:在“孤儿”财产中无价值的每个实体都将被列入我的清单的最后索引(即不注意有多少实体能够无价值,不注意在无价值的实体之间分类)。

这是我的法典:

myList.Select(Map).OrderBy(a => a.SortOrder).ToList();

结果是:

[
  {
    "SortOrder": null
  },
  {
    "SortOrder" : 2
  }
]

但这是我所希望的,我不知道如何执行:

[
  {
    "SortOrder": 2
  },
  {
    "SortOrder" : null
  }
]
最佳回答

你们可以通过像以下那样的trick来做到这一点。

List<MyEntity> myList = new List<MyEntity>
{
    new MyEntity { SortOrder = 2 },
    new MyEntity { SortOrder = null },
    new MyEntity { SortOrder = 1 },
};


List<MyEntity> sortedList = myList.OrderBy(e => e.SortOrder ?? int.MaxValue).ToList();
问题回答

虽然“VivekNuna”的答案是可行的,而且可能是最简单的,但使用一种习俗比较器是比较的。

var comparer = Comparer<YourMapClass>.Create((a, b) =>
    a.SortOrder.HasValue
    ? b.SortOrder.HasValue
      ? a.SortOrder.Value.CompareTo(b.SortOrder.Value)
      : -1
    : 1
);
myList
  .Select(Map)
  .Order(comparer)
  .ToList();

或确定同一名单

myList.Sort(comparer);

You can alternatively create a comparer for int?

var comparer = Comparer<int?>.Create((a, b) =>
    a.HasValue
    ? b.HasValue
      ? a.Value.CompareTo(b.Value)
      : -1
    : 1
);

并且

myList
  .Select(Map)
  .OrderBy(e => e.SortOrder, comparer)
  .ToList();




相关问题
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. ...

热门标签