聲明:閱讀本文需要 C# 泛型和委托的基本知識。
大家好!
清單在程式設計過程中應用極為廣泛,而按照索引來查找顯然不能滿足所有需求, C#.NET 提供了很好的内建方法來友善程式員編寫按照特性來搜尋清單中的成員的代碼。
下面我将介紹該方法。
在 List 類中,有幾個方 :FindIndex 、 FindAll、Find、FindIndexLast、FindLast 。
FindIndex 方法的參數是一個委托,該委托是 Predicate<T> 類型的,接受一個 T 類型的參數,傳回一個布爾值。其他方法的參數也是如此。
Predicate<T> 的定義如下:
public delegate bool Predicate<T>(T object)
方法簽名如下:
public int FindIndex(Predicate<T> func)
這幾個方法會将清單中的每一項作為參數,傳遞給該委托。 FindIndex 會傳回第一個在委托中傳回布爾值的對象的索引,并停止查找;FindAll 則會一直查找到結束為止,并傳回一個 T 類型的清單;Find 則會傳回第一個符合條件的T 類型的對象,并結束查找;FindIndexLast 和 FindLast 是從後向前查找,功能分别和 FindIndex 及 Find 對應。
下面用一個示例來說明(由于這幾個函數用法都一樣,隻是傳回類型不同,就隻拿 FindIndex 和 FindAll 來說明):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FindFeature
{
//定義球隊類
class FootballTeam
{
private String name; //球隊名
private int winnerCount; //冠軍次數
private int level; //等級
public String Name { get; set; }
public int WinnerCount { get; set; }
public int Level { get; set; }
//3個參數的構造函數
public FootballTeam(String name, int winnerCount, int level)
{
this.Name = name;
this.WinnerCount = winnerCount;
this.Level = level;
}
//1個參數的構造函數
public FootballTeam(String name)
{
this.Name = name;
}
//按照球隊名查找
public bool FindName(FootballTeam footballTeam)
{
if (this.Name == footballTeam.Name)
{
return true;
}
else
{
return false;
}
}
//按照奪冠次數查找
public static bool FindWinnerCount(FootballTeam footballTeam)
{
if (footballTeam.WinnerCount > 0)
{
return true;
}
else
{
return false;
}
}
}
class Program
{
static void Main(string[] args)
{
//建構清單并向其中添加4個成員
List<FootballTeam> teams = new List<FootballTeam>();
teams.Add(new FootballTeam("A", 3, 1));
teams.Add(new FootballTeam("B", 4, 1));
teams.Add(new FootballTeam("C", 2, 2));
teams.Add(new FootballTeam("D", 4, 2));
teams.Add(new FootballTeam("E", 0, 1));
//查找球隊名為 "B" 的對象
int ind = teams.FindIndex(new FootballTeam("B").FindName);
//也可以使用lambda表達式(lambda 表達式本文不贅述),代碼如下:
//int ind = teams.FindIndex(r => r.Name == "B");
Console.WriteLine(teams[ind].Name);
Console.WriteLine();
//查找球隊奪冠次數大于0的對象,并傳回一個清單
List<FootballTeam> winners = new List<FootballTeam>();
winners = teams.FindAll(FootballTeam.FindWinnerCount);
//也可以使用lambda表達式,代碼如下:
//winners = teams.FindAll(r => r.WinnerCount > 0);
winners.ForEach(r => Console.WriteLine("{0} winner counts:{1}",r.Name,r.WinnerCount));
Console.ReadKey();
}
}
}
運作結果如下:
謝謝閱讀!
Rember !You Make Luck !