簡體   English   中英

按字母順序對動態下拉列表排序

[英]Sort dynamic dropdown list alphabetically

我有一個下拉列表,每個項目的水平三個字符串。 我怎樣才能按字母順序首先從每個項目的字符串1排序,然后再從每個項目的字符串2排序?

這是我的片段:

foreach (var item in list)
{
    if(typeof(T).Equals(typeof(Machine)))
    {
        Machine machine = (item as Machine);
        string title = machine.MachineName + " - " + machine.Serial + " - " + machine.MachineOwnership;
        alert.AddAction(UIAlertAction.Create(title, UIAlertActionStyle.Default, action => {
            button.SetTitle(title, UIControlState.Normal);
        }));
    }
    else if(typeof(T).Equals(typeof(Person)))
    {
        alert.AddAction(UIAlertAction.Create((item as Person).Name, UIAlertActionStyle.Default, action => {
            button.SetTitle((item as Person).Name, UIControlState.Normal);
        }));
    }
}

其中list包含類型為Machine對象,該對象具有以下屬性:

MachineNameSerialMachineOwnshership (所有字符串)。

因此,我想執行類似OrderBy(MachineName).ThenBy(Serial)但是在我先檢查列表類型是什么,然后填充每個項目的下拉列表時,不確定如何正確執行操作。

如果有人需要澄清,我的下拉列表看起來像這樣:

-------------------------------------------------
MachineNameStartsWithA - 01234 - OwnerStartsWithA
--------------------------------------------------
MachineNameStartsWithB - 012345 - OwnerStartsWithB
---------------------------------------------------

等等...這是一長串的項目,其中的字符串用“-”分隔,如代碼中所示。

此外,它的價值在於,它當前在Xamarin應用程序內部。

我認為這樣的事情應該起作用。 Tuple排序應按字典順序:

list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial))

OfType調用還應該消除對typeof檢查和typeof的需要-結果應該是Machine的可迭代項。


關於多種對象類型的注釋:

將類似類型分組在一起

從UI / UX角度來看,這將是我的默認首選項,除非將MachinePerson混合在一起確實很有意義。 根據list的長度,最好先將元素類型拆分為list.OfType都會枚舉整個列表。

foreach(var item in list.OfType<Machine>().OrderBy(x => new Tuple<string,string>(x.MachineName,x.Serial)))
{
  // append item
}
foreach(var item in list.OfType<Person>().OrderBy(x => x.Name))
{
  // append item
}

交織各種類型

private Tuple<string,string> Projection(BaseClass x)
{
    Machine item = x as Machine;
    if(item != null)
    {
      return new Tuple<string,string>(item.MachineName,item.Serial);
    }

    Person item = x as Person;
    if(item != null)
    {
      return new Tuple<string,string>(item.Name,"");
    }
}

foreach(var item in list.OrderBy(Projection))
{
  // check type of item and append as appropriate
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM