【问题标题】:C# Merge 2 list of IPC# Merge 2 列表的IP
【发布时间】:2016-12-05 12:14:53
【问题描述】:

我在使用这个模型:

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.x (104.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

【问题讨论】:

  • 为什么不NewIPList = IPList.Where(x=&gt;x.ip.StartsWith("104.130.124.")).ToList()
  • 我能发现的第一件事是,删除 total_websites 的 setter 并在 getter 中使用网站。
  • 为什么不使用IPAddress 而不是String 作为Ip 属性?

标签: c# linq merge


【解决方案1】:

你可以试试关注

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();

【讨论】:

  • 谢谢,看起来比我的解决方案更好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2017-04-13
  • 2020-08-17
  • 2015-11-16
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
相关资源
最近更新 更多