C#中List的Find方法的使用

时间:2023-03-24 21:16:32

查找List中的某个值,可以使用循环遍历对比,查找出结果。C#中提供了Find方法,可以直接使用,只要查找条件传入就可。如下:

public class RecordInfo
{
private string recordID = string.Empty;
private string itemID = string.Empty;
private string recordAndItemID = string.Empty;
private string value = string.Empty;

public string RecordID
{
get
{
return this.recordID;
}
}

public string ItemID
{
get
{
return this.itemID;
}
}

public string RecordAndItemID
{
get
{
return this.recordAndItemID;
}
}

public string Value
{
get
{
return this.value;
}
}

public RecordInfo(string tmprecordID, string tmpitemID, string tmprecordAndItemID, string tmpvalue)
{
this.recordID = tmprecordID;
this.itemID = tmpitemID;
this.recordAndItemID = tmprecordAndItemID;
this.value = tmpvalue;
}
}

  1. class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. List<User> userCollection = new List<User>();
  6. userCollection.Add(new User(1, "testOne"));
  7. userCollection.Add(new User(2, "testTwo"));
  8. userCollection.Add(new User(3, "testThree"));
  9. User resultUser = userCollection.Find(
  10. delegate(User user)
  11. {
  12. //return user.UserID == 0;
  13. return user.UserID == 1 && user.UserName.Equals("testOne");
  14. });
  15. Console.WriteLine(resultUser != null ?
  16. resultUser.UserID + System.Environment.NewLine + resultUser.UserName : "没有查找到");
  17. Console.ReadLine();
  18. }
  19. }
  20. public class User
  21. {
  22. private int userID = 0;
  23. private string userName = string.Empty;
  24. public int UserID
  25. {
  26. get
  27. {
  28. return this.userID;
  29. }
  30. }
  31. public string UserName
  32. {
  33. get
  34. {
  35. return this.userName;
  36. }
  37. }
  38. public User(int userID, string userName)
  39. {
  40. this.userID = userID;
  41. this.userName = userName;
  42. }
  43. }