如何在c#中搜索对象列表

本文关键字:搜索 对象 列表 | 更新日期: 2023-09-27 17:53:37

我仍在学习c#,并试图构建一个nic列表,我可以稍后在我的代码中引用它来执行misc。功能。无论如何,我能够很好地填充列表,但现在的问题是,我不确定在列表中搜索具有特定标准的NIC对象的最佳方式。我可以让foreach循环工作,但我不确定这是否是最好的方法。我已经搜索了这个主题,并找到了一堆关于如何使用LINQ或Lambdas进行高级搜索的材料,但对于初级程序员来说,这些工作没有任何好的信息。

下面是我创建对象和列表的代码,以及我想要完成的伪代码:

//Constructs a NIC structure and a list to store NICs (my actual code)
struct NIC
{
    public string nicName;
    public string nicIp;
    public string nicGateway;
    public string nicMask;
}
List<NIC> nicList = new List<NIC>();


//Example searches in semi pseudocode
if nicList contains any NIC where anyNIC.nicIp first three chars .Contains("169")
{
//Do something
}

if nicList contains any NIC where anyNIC.nicIP != null 
{
//Do something
}

-谢谢

如何在c#中搜索对象列表

LINQ即将成为你最好的朋友。在这种情况下,我将使用Enumerable.Any方法。Enumerable.AnyIEnumerable<T>的扩展方法,因此您可以直接在nicList上调用它。您向它传递一个函数,该函数接受NIC的实例并返回truefalse

下面是在你的特定情况下的样子:

if (nicList.Any(x => x.nicIp.StartsWith("169"))
{
   // Do something
}

if (nicList.Any(x => !string.IsNullOrEmpty(x.nicIP))
{
   // Do something
}

在本例中,如果有一个或多个元素满足条件,Enumerable.Any只返回true。如果您想访问满足条件的元素,请使用LINQ方法Enumerable.Where。签名是相同的,但它返回的不是bool,而是IEnumerable<T>

的例子:

var nicsWithIp = nicList.Where(x => !string.IsNullOrEmpty(x.nicIP);

有关更多信息,请查看此MSDN页面:"Getting Started with LINQ in c# "。

use LINQ:

var nics = nicList.Where(n => n.nicIp.Substring(0, 3) == "169").ToList();

如何:

if(nicList.Where(n => n.nicIp.Substring(0, 3) == "169").Any())
{
}

if(nicList.Where(n => n.nicIp != null).Any())
{
}

在第一个检查中添加null检查可能是明智的,以防止出现NullReferenceException:

if(nicList.Where(n => n.nicIp != null && n.nicIp.Substring(0, 3) == "169").Any())
{
}

使用LINQ框架有几种方法。

您可以使用内联查询语法:
// Get all NICs with 169.x.x.x IP address
var nic169 = from nic in nicList
              where nic.nicIp != null && nic.nicIp.StartsWith("169")
              select nic;
var contains169Ip = nic169.Count() > 0;
// Get all NICs with non-null, non-empty IP address    
var validIpNics = from nic in nicList
                   where !string.IsNullOrWhiteSpace(nic.nicIp)
                   select nic;

或者,您可以使用lambda语法与LINQ方法:

// Do we have a 169.x.x.x NIC present?
var has169 = nicList.Any(nic => nic.nicIp != null && nic.nicIp.StartWith("169"));
// First NIC with a non-null, non-empty IP address
var firstNic = nicList.First(nic => !string.IsNullOrWhiteSpace(nic.nicIp));

为了更好地解释lambda表达式,取Func<string,bool>delegate类型。这意味着"是一个接受字符串的方法,返回一个bool值"。此方法在.Any()方法中用作选择器,以确定是否任何对象匹配。

var func = (text) => { return !string.IsNullOrWhiteSpace(text); }

直接等价于:

bool OurLambdaFunc(string text) { return !string.IsNullOrWhiteSpace(text); }

.Any<T>(Func<T,bool> selector)方法展开成这样:

public bool Any<T>(IEnumerable<T> collection, Func<T, bool> selector)
{
  foreach(var value in collection)
    if(selector(value))
      return true;  // Something matched the selector method's criteria.
  // Nothing matched our selector method's criteria.
  return false;
}
相关文章: