gpt4 book ai didi

c# - 在 foreach 中访问 LINQ Select 中使用的值

转载 作者:行者123 更新时间:2023-12-04 15:05:34 25 4
gpt4 key购买 nike

给定一个 IP 地址列表:

List<string> ipList = new List<string>(); //example: 192.168.0.1, 192.168.0.2, 192.168.0.3 etc.

我试图以并行方式遍历列表中的每个 IP,然后在屏幕上打印一条有意义的消息:

foreach (PingReply pingReply in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new Ping().Send(ip)))
{
Console.WriteLine($"Ping status: {pingReply.Status} for the target IP address: {ip}");
}

我无法在该上下文中访问 ip。我真的很想了解如何在发送给他们时访问每个亲戚 ip

我探索了 PingReply对象但是PingReply.Address例如包含主机(发件人)IP,因此它无法满足此要求。我真的希望 PingReply 对象包含被 ping 的 Ip!


更新

根据@haim770 和@MindSwipe 提供的示例,我最终使用了:

foreach (var pingResponseData in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new { ip, pingReply = new Ping().Send(ip) }))
{
Console.WriteLine($"Ping status: {pingResponseData.pingReply.Status} for the target IP address: {pingResponseData.ip}");
}

更新 2

根据@pinkfloydx33 关于使用ValueTuple 的评论,我已经按照以下示例完成:

foreach (var (ip, reply) in ipList.AsParallel().WithDegreeOfParallelism(ipList.Count).Select(ip => (ip, new Ping().Send(ip, 150))))
{
Console.WriteLine($"Ping status: {reply.Status} for the target IP address: {ip}");
}

最佳答案

您目前只选择了 pingReply,而不是 ippingReply,为此您需要选择一个新anonymous type并迭代它。像这样:

foreach (var (pingReply, ip) in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => (ip, Ping().Send(ip))))
{
// Here 'i' is an object with the properties 'ip' and 'pingReply'
Console.WriteLine($"Ping status: {i.pingReply.Status} for the target IP address: {i.ip}");
}

编辑: 现在才注意到 haim770基本上是在 their comment 中发布的

编辑 2: 谢谢 pinkfloydx33指出我可以使用 tuple deconsturcting

关于c# - 在 foreach 中访问 LINQ Select 中使用的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66220520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com