【发布时间】: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=>x.ip.StartsWith("104.130.124.")).ToList()? -
我能发现的第一件事是,删除 total_websites 的 setter 并在 getter 中使用网站。
-
为什么不使用
IPAddress而不是String作为Ip属性?