按IP

时间:2016-04-22 10:08:21

标签: c# sorting

我有一个包含

类型数据的ListView

class InfoItem { public string IP { get; set; } public string MAC { get; set; } public string HOST { get; set; } }

事件处理程序PingCompletedCallback以随机方式获取IP,因此我们无法预测Ips的顺序。我们需要对它们进行排序。我正在使用这个

if (!Dispatcher.CheckAccess())
            {

                Dispatcher.Invoke(new Action(() =>
                {
                    lstNetworks.Items.Add(new InfoItem() { IP = e.Reply.Address.ToString(), MAC = macAdress, HOST = hostName });
                    lstNetworks.Items.SortDescriptions.Add(new SortDescription("IP", ListSortDirection.Ascending));
                }));
            }

它部分有效,但结果看起来像这样

192.168.1.1 192.168.1.10 192.168.1.2 192.168.1.254 192.168.1.3 等等...

我们如何以正确的方式对此ListView项进行排序

192.168.1.1    192.168.1.2    192.168.1.3    192.168.1.10    192.168.1.254

更新。我试着在那个问题上做:

List<InfoItem> list = new List<InfoItem>(); 
foreach (var item in lstNetworks.Items) { 
list.Add(item as InfoItem); 
} 
List<InfoItem> list2 = new List<InfoItem>(); 
list2 = list.Select(Version.Parse).OrderBy(arg => arg).Select(arg => arg.ToString()).ToList(); 

但它给了我和异常方法Select的类型参数不能从用法中推断出来。

2 个答案:

答案 0 :(得分:0)

如其他答案中所述,您可以使用public class Thing { public string ip; } var list = new List<Thing>() { new Thing() { ip = "192.168.1.1" }, new Thing() { ip = "192.168.1.10" }, new Thing() { ip = "192.168.1.2" }, new Thing() { ip = "192.168.1.254" }, new Thing() { ip = "192.168.1.3" } }; var sorted = list.OrderBy(item => Version.Parse(item.ip)); foreach (var item in sorted) { Console.WriteLine(item.ip); } 来执行此操作:

'declare some collection, which will contain modules
For Each vbc In ThisWorkbook.VBProject.VBComponents
   if vbc.Type = 1 then
       'add to temporary collection ... for example for name, use vbc.name
   end if
Next

答案 1 :(得分:0)

您可以使用客户IComparable类

public class MyIP : IComparable<MyIP>
{
    List<int>subAddress = null;
    public MyIP(string IPstr)
    {
       subAddress = IPstr.Split(new char[] {'.'}).Select(x => int.Parse(x)).ToList();
    }
    public int CompareTo(MyIP other)
    {
       int results = 0
       if(this.subAddress[0] != other.subAddress[0])
       {
          results = this.subAddress[0].CompareTo(other.subAddress[0]);
       }
       else
       {
          if(this.subAddress[1] != other.subAddress[1])
          {
             results = this.subAddress[1].CompareTo(other.subAddress[1]);
          }
          else
          {
             if(this.subAddress[2] != other.subAddress[2])
             {
                results = this.subAddress[2].CompareTo(other.subAddress[2]);
             }
             else
             {
                results = this.subAddress[3].CompareTo(other.subAddress[3]);
             }
          }
       }
       return results;
    }

}​