C#Merge 2 IP列表

时间:2016-12-05 12:14:54

标签: c# linq merge

我使用这个模型:

public class IPList
{
    public List<string> websites { get; set; }
    public int total_websites { get; set; }
    public string ip { get; set; }
}

该列表具有以下值:

[{
    "websites": ["test1.com", "test2.com", "test3.com", "test4.com"],
    "total_websites": 4,
    "ip": "104.130.124.96"
}, {
    "websites": ["test5.com"],
    "total_websites": 1,
    "ip": "104.130.124.80"
}, {
    "websites": ["test6.com"],
    "total_websites": 1,
    "ip": "104.130.124.70"
}]

我想要一个包含范围104.130.124.x104.130.124.0 to 104.130.124.255)中所有IP的新列表。

我做了什么:

List<IPList> NewIPList = new List<IPList>();
for (int i = 0; i < 255; i++)
{
    string TempIP = "104.130.124." + i;
    IPListTake10 TempIpList = IPList.Where(p => p.ip == TempIP).FirstOrDefault();
    if (TempIpList != null)
    {
        NewIPList.Add(new IPList{ ip = TempIP, total_websites = TempIpList.total_websites, websites = TempIpList.websites });
    }
    else
    {
        NewIPList.Add(new IPList{ ip = TempIP, total_websites = 0});
    }
}

有更好的方法吗?

可能使用以下方法之一: http://alicebobandmallory.com/articles/2012/10/18/merge-collections-without-duplicates-in-c

  • 列表和LINQ合并
  • 字典合并
  • HashSet和IEqualityComparer
  • LINQ Union和IEqualityComparer

1 个答案:

答案 0 :(得分:2)

你可以试试

var IPList = new List<IPList>() { new IPList() {ip="104.130.124.10", total_websites=10}};

var NewIPList = Enumerable.Range(0, 256)
        .Select(x => $"104.130.124.{x}")
        .Select(x => IPList.FirstOrDefault(z => z.ip == x) ?? new IPList() {ip=x, total_websites=0})
        .ToList();