【问题标题】:How can I use conditonal operator in OrderBy function [duplicate]如何在 OrderBy 函数中使用条件运算符 [重复]
【发布时间】:2021-07-01 09:31:06
【问题描述】:
bookingInfo.CreditCardList = airUserCreditCardList
  .Distinct()
  .OrderBy(o => o.Text)
  .ToList();

我正在尝试根据 Text 属性中的值对列表进行排序。有没有一种方法可以仅在对象的属性 Text 的值为“Primary”时才能对列表进行排序。

我的列表是这样的


     Text="abc",Code="123"----0th index
        Text ="Select",Code="1233"--1st Index
        Text="Primary",Code="0000"--2ndIndex```

But i want it to look like this only if the Primary card is present in the list 

    ```
Text="Primary",Code="0000"--0th Index
    Text ="Select",Code="1233"--1st Index
        Text ="abc",Code="123"--2nd Index

【问题讨论】:

  • 您能否举一些例子说明“仅当 Text 的值为主要时才对列表进行排序,否则不应发生排序”?
  • 不清楚,如果您只想按记录排序哪些文本是“主要”,您的意思是您想先查看所有“主要”信用卡然后休息?
  • 不清楚什么是“如果Text 的值是主要的”。像这样的东西:.OrderBy(o => o.Text != "primary")
  • 如果“Primary”在列表中,为什么“abc”出现在“Select”之后?我知道“Primary”排在第一位,但如果您按Text 订购,则“abc”一词将位于“Select”之前。这也不是原来的顺序,所以似乎突然“abc”无缘无故地出现在最后。解释规则。

标签: c#


【解决方案1】:

您可以按bool 值订购(但请注意,false < true):

  bookingInfo.CreditCardList = airUserCreditCardList
    .Distinct()
    .OrderBy(o => !o.Text.Contains("Text=\"Primary\""))
    .ToList();

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2020-01-07
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2012-03-14
    • 2021-04-22
    相关资源
    最近更新 更多