すべてのIPアドレスをC#のIPアドレス配列に昇順で配置する方法私はIPアドレスクラスの配列を持っています
ipaddress[] device = new ipaddress[10];
IP値が違うので昇順で並べたい
バージョン トリックを使用できます。
サンプルデータ:
IPAddress[] ips = new[]{
IPAddress.Parse("192.168.1.4"),
IPAddress.Parse("192.168.1.5"),
IPAddress.Parse("192.168.2.1"),
IPAddress.Parse("10.152.16.23"),
IPAddress.Parse("69.52.220.44"),
};
昇順:
var sortedIps = ips
.Select(ip => Version.Parse(ip.ToString()))
.OrderBy(v => v)
.Select(v => IPAddress.Parse(v.ToString()))
.ToArray();
結果:
{10.152.16.23} System.Net.IPAddress
{69.52.220.44} System.Net.IPAddress
{192.168.1.4} System.Net.IPAddress
{192.168.1.5} System.Net.IPAddress
{192.168.2.1} System.Net.IPAddress
アップデート
あなた: 「System.Version」に「Parse」の定義が含まれていないというエラーが表示されます。私: では、少なくとも .NET Framework 4.0 を使用していないということですね。 Version.Parse あなた: はい、.NET フレームワーク 3.5 を使用しています。どのような変更を行う必要がありますか?
IPAddress.GetAddressBytes
次に、 for Enumerable.OrderBy
/を使用できます ThenBy
。
sortedIps = ips
.Select(ip => new { IP = ip, Bytes = ip.GetAddressBytes() })
.OrderBy(x => x.Bytes[0]).ThenBy(x => x.Bytes[1]).ThenBy(x => x.Bytes[2]).ThenBy(x => x.Bytes[3])
.Select(x => x.IP)
.ToArray();
Update2
ありがとうございます。ただし、配列のいずれかのメンバーが null の場合は停止します。null 値を含む配列を操作したい場合。null 値を最後に並べたい。
次に、null 値にByte[]
withを使用する次のクエリを使用します。Byte.MaxValue
var sortedIps = ips
.Select(ip => new {
IP = ip,
Bytes = ip == null
? new[] { Byte.MaxValue, Byte.MaxValue, Byte.MaxValue, Byte.MaxValue }
: ip.GetAddressBytes()
})
.OrderBy(x => x.Bytes[0]).ThenBy(x => x.Bytes[1]).ThenBy(x => x.Bytes[2]).ThenBy(x => x.Bytes[3])
.Select(x => x.IP)
.ToArray();
これはうまくいくはずです:
Array.Sort(devices, (d1, d2) => d1.IPValue.CompareTo(d2.IPValue));
しかし、List
代わりに使用することをお勧めしますArray
私が正しければ、これを行うことができます:
var list = new string[5];
list = list.OrderByDescending(x => x).ToArray();
そのためにLinqを使用できます
using System.Linq;
ipaddress[] sortedDevice1 = device.OrderBy(d => d.IP).ToArray(); // assuming the ip address is saved in a field named 'IP'
ipaddress[] sortedDevice2 = device.OrderByDescending(d => d.IP).ToArray(); // if you need it sorted by descending order
IP
フィールドが でない場合は、フィールドのインターフェイスstring
を実装して、並べ替えの品質を向上させることができます。つまり、 getの代わりにIComparable
IP
11.100 > 2.100
2.100 > 11.100
Array.Sort メソッドの 1 つ、とりわけ Array.Sort メソッドを使用します。例は簡単です:
Array.Sort(device, (a,b) => [compare here, return int] );