Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing value used in LINQ Select within a foreach

Tags:

c#

linq

plinq

Given a list of IP addresses:

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

I am attempting to loop over each IP in the list, in a parallel fashion and then print a meaningful message to screen:

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}");
}

I am unable to access ip in that context. I would really like to understand how I could go about accessing each relative ip as I am sending them out?

I have explored the PingReply object but PingReply.Address as an example contains the host (sender) IP, so it cannot help with this requirement. I really wish the PingReply object contained the Ip that was pinged!


UPDATE

As per example provided by @haim770 and @MindSwipe I ended up using:

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}");
}

UPDATE 2

As per comment from @pinkfloydx33 regarding use of ValueTuple I have done as per the following example:

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}");
}
like image 871
BernardV Avatar asked Nov 19 '25 07:11

BernardV


1 Answers

You're currently only selecting the pingReply, not the ip and the pingReply, to do that you'll need to select a new anonymous type and iterate over that. Like so:

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}");
}

Edit: Just noticed now that haim770 posted basically this in their comment

Edit 2: Thanks pinkfloydx33 for pointing out I could use tuple deconsturcting

like image 103
MindSwipe Avatar answered Nov 21 '25 19:11

MindSwipe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!