gpt4 book ai didi

c# - 将 Linq 转换为常规函数

转载 作者:太空狗 更新时间:2023-10-30 01:06:16 25 4
gpt4 key购买 nike

我有这个 linq 方法如何获取所有机器网卡属性,我不想使用 linq,我可以得到一些帮助来转换它而不使用 Linq 吗?

public NetworkAdapter[] GetAll()
{
return (from adapter in NetworkInterface.GetAllNetworkInterfaces()
from uniCast in adapter.GetIPProperties().UnicastAddresses
where !System.Net.IPAddress.IsLoopback(uniCast.Address) && uniCast.Address.AddressFamily != AddressFamily.InterNetworkV6
let lastGatewayAddress = adapter.GetIPProperties().GatewayAddresses.LastOrDefault()
select new NetworkAdapter()
{
string Name = adapter.Name,
string ID = adapter.Id,
string Description = adapter.Description,
string IPAddress = uniCast.Address.ToString(),
string NetworkInterfaceType = adapter.NetworkInterfaceType.ToString(),
string Speed = adapter.Speed.ToString("#,##0"),
string MacAddress = getMacAddress(adapter.GetPhysicalAddress().ToString()),
string gatewayIpAddress = string.Join(" ", adapter.GetIPProperties().GatewayAddresses.Select(a => a.Address))
}).ToArray();
}

这是我尝试过的;

public void get()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface adapter in nics)
{
Description = adapter.Description;
Name = adapter.Name;
MacAddress = adapter.GetPhysicalAddress().ToString();

IPInterfaceProperties ips = adapter.GetIPProperties();
UnicastIPAddressInformationCollection uniCast = ips.UnicastAddresses;

foreach (UnicastIPAddressInformation ipInfo in uniCast)
{
if (ipInfo.Address.AddressFamily != AddressFamily.InterNetworkV6)
{

}
}

}
}

最佳答案

虽然我不明白为什么,但还是这样。

在我的 friend ReSharper 的帮助下(以及我的输入,因为 ReSharper 无法做到这一切):

public NetworkAdapter[] GetAll()
{
List<NetworkAdapter> list = new List<NetworkAdapter>();
foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
foreach (UnicastIPAddressInformation uniCast in adapter.GetIPProperties().UnicastAddresses)
{
if (!System.Net.IPAddress.IsLoopback(uniCast.Address) && uniCast.Address.AddressFamily != AddressFamily.InterNetworkV6)
{
StringBuilder gatewayIPAddresses = new StringBuilder();
string gatewayIPAddressesDisplay = string.Empty;
foreach (var address in adapter.GetIPProperties().GatewayAddresses)
{
gatewayIPAddresses.Append(address.Address);
gatewayIPAddresses.Append(" ");
}

if (gatewayIPAddresses.Length > 0)
{
gatewayIPAddressesDisplay = gatewayIPAddresses.ToString().TrimEnd(' ');
}

list.Add(new NetworkAdapter()
{
Name = adapter.Name,
ID = adapter.Id,
Description = adapter.Description,
IPAddress = uniCast.Address.ToString(),
NetworkInterfaceType = adapter.NetworkInterfaceType.ToString(),
Speed = adapter.Speed.ToString("#,##0"),
MacAddress = getMacAddress(adapter.GetPhysicalAddress().ToString()),
gatewayIpAddress = gatewayIPAddressesDisplay
});
}
}
return list.ToArray();
}

关于c# - 将 Linq 转换为常规函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080196/

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