List<T>.FindLastIndex Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Recherche un élément qui correspond aux conditions définies par un prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans la List<T> ou une partie de celui-ci.
Surcharges
| Nom | Description |
|---|---|
| FindLastIndex(Predicate<T>) |
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans l’ensemble List<T>. |
| FindLastIndex(Int32, Predicate<T>) |
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans la plage d’éléments de l’élément List<T> qui s’étend du premier élément à l’index spécifié. |
| FindLastIndex(Int32, Int32, Predicate<T>) |
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans la plage d’éléments dans la List<T> plage d’éléments qui contient le nombre spécifié d’éléments et se termine à l’index spécifié. |
FindLastIndex(Predicate<T>)
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans l’ensemble List<T>.
public:
int FindLastIndex(Predicate<T> ^ match);
public int FindLastIndex(Predicate<T> match);
member this.FindLastIndex : Predicate<'T> -> int
Public Function FindLastIndex (match As Predicate(Of T)) As Integer
Paramètres
- match
- Predicate<T>
Délégué Predicate<T> qui définit les conditions de l’élément à rechercher.
Retours
Index de base zéro de la dernière occurrence d’un élément qui correspond aux conditions définies par match, s’il est trouvé ; sinon, -1.
Exceptions
match a la valeur null.
Exemples
L’exemple suivant illustre les méthodes de recherche pour la List<T> classe. L’exemple de la List<T> classe contient des book objets, de classe Book, à l’aide des données de l’exemple de fichier XML : Books (LINQ to XML). La FillList méthode de l’exemple utilise LINQ to XML pour analyser les valeurs du code XML aux valeurs de propriété des book objets.
Le tableau suivant décrit les exemples fournis pour les méthodes de recherche.
| Méthode | Example |
|---|---|
| Find(Predicate<T>) | Recherche un livre par ID à l’aide du IDToFind délégué de prédicat.L’exemple C# utilise un délégué anonyme. |
| FindAll(Predicate<T>) | Recherchez tous les livres dont Genre la propriété est « Computer » à l’aide du FindComputer délégué de prédicat. |
| FindLast(Predicate<T>) | Recherche le dernier livre de la collection dont la date de publication est antérieure à 2001, à l’aide du PubBefore2001 délégué de prédicat.L’exemple C# utilise un délégué anonyme. |
| FindIndex(Predicate<T>) | Recherche l’index du premier carnet d’ordinateurs à l’aide du FindComputer délégué de prédicat. |
| FindLastIndex(Predicate<T>) | Recherche l’index du dernier carnet d’ordinateurs à l’aide du FindComputer délégué de prédicat. |
| FindIndex(Int32, Int32, Predicate<T>) | Recherche l’index du premier carnet d’ordinateurs dans la deuxième moitié de la collection, à l’aide du FindComputer délégué de prédicat. |
| FindLastIndex(Int32, Int32, Predicate<T>) | Recherche l’index du dernier livre informatique dans la deuxième moitié de la collection, à l’aide du FindComputer délégué de prédicat. |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Find
{
class Program
{
private static string IDtoFind = "bk109";
private static List<Book> Books = new List<Book>();
public static void Main(string[] args)
{
FillList();
// Find a book by its ID.
Book result = Books.Find(
delegate(Book bk)
{
return bk.ID == IDtoFind;
}
);
if (result != null)
{
DisplayResult(result, "Find by ID: " + IDtoFind);
}
else
{
Console.WriteLine("\nNot found: {0}", IDtoFind);
}
// Find last book in collection published before 2001.
result = Books.FindLast(
delegate(Book bk)
{
DateTime year2001 = new DateTime(2001,01,01);
return bk.Publish_date < year2001;
});
if (result != null)
{
DisplayResult(result, "Last book in collection published before 2001:");
}
else
{
Console.WriteLine("\nNot found: {0}", IDtoFind);
}
// Find all computer books.
List<Book> results = Books.FindAll(FindComputer);
if (results.Count != 0)
{
DisplayResults(results, "All computer:");
}
else
{
Console.WriteLine("\nNo books found.");
}
// Find all books under $10.00.
results = Books.FindAll(
delegate(Book bk)
{
return bk.Price < 10.00;
}
);
if (results.Count != 0)
{
DisplayResults(results, "Books under $10:");
}
else
{
Console.WriteLine("\nNo books found.");
}
// Find index values.
Console.WriteLine();
int ndx = Books.FindIndex(FindComputer);
Console.WriteLine("Index of first computer book: {0}", ndx);
ndx = Books.FindLastIndex(FindComputer);
Console.WriteLine("Index of last computer book: {0}", ndx);
int mid = Books.Count / 2;
ndx = Books.FindIndex(mid, mid, FindComputer);
Console.WriteLine("Index of first computer book in the second half of the collection: {0}", ndx);
ndx = Books.FindLastIndex(Books.Count - 1, mid, FindComputer);
Console.WriteLine("Index of last computer book in the second half of the collection: {0}", ndx);
}
// Populates the list with sample data.
private static void FillList()
{
// Create XML elements from a source file.
XElement xTree = XElement.Load(@"c:\temp\books.xml");
// Create an enumerable collection of the elements.
IEnumerable<XElement> elements = xTree.Elements();
// Evaluate each element and set set values in the book object.
foreach (XElement el in elements)
{
Book book = new Book();
book.ID = el.Attribute("id").Value;
IEnumerable<XElement> props = el.Elements();
foreach (XElement p in props)
{
if (p.Name.ToString().ToLower() == "author")
{
book.Author = p.Value;
}
else if (p.Name.ToString().ToLower() == "title")
{
book.Title = p.Value;
}
else if (p.Name.ToString().ToLower() == "genre")
{
book.Genre = p.Value;
}
else if (p.Name.ToString().ToLower() == "price")
{
book.Price = Convert.ToDouble(p.Value);
}
else if (p.Name.ToString().ToLower() == "publish_date")
{
book.Publish_date = Convert.ToDateTime(p.Value);
}
else if (p.Name.ToString().ToLower() == "description")
{
book.Description = p.Value;
}
}
Books.Add(book);
}
DisplayResults(Books, "All books:");
}
// Explicit predicate delegate.
private static bool FindComputer(Book bk)
{
if (bk.Genre == "Computer")
{
return true;
}
else
{
return false;
}
}
private static void DisplayResult(Book result, string title)
{
Console.WriteLine();
Console.WriteLine(title);
Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", result.ID,
result.Author, result.Title, result.Genre, result.Price,
result.Publish_date.ToShortDateString());
Console.WriteLine();
}
private static void DisplayResults(List<Book> results, string title)
{
Console.WriteLine();
Console.WriteLine(title);
foreach (Book b in results)
{
Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", b.ID,
b.Author, b.Title, b.Genre, b.Price,
b.Publish_date.ToShortDateString());
}
Console.WriteLine();
}
}
public class Book
{
public string ID { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public double Price { get; set; }
public DateTime Publish_date { get; set; }
public string Description { get; set; }
}
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1
Private IDToFind As String = "bk109"
Public Books As New List(Of Book)
Sub Main()
FillList()
' Find a book by its ID.
Dim result As Book = Books.Find(AddressOf FindID)
If result IsNot Nothing Then
DisplayResult(result, "Find by ID: " & IDToFind)
Else
Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
End If
Console.WriteLine()
' Find last book in collection that has a publish date before 2001.
result = Books.FindLast(AddressOf PubBefore2001)
If result IsNot Nothing Then
DisplayResult(result, "Last book in collection published before 2001:")
Else
Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
End If
Console.WriteLine()
' Find all computer books.
Dim results As List(Of Book) = Books.FindAll(AddressOf FindComputer)
If results.Count <> 0 Then
DisplayResults(results, "All computer books:")
Else
Console.WriteLine(vbCrLf & "No books found.")
End If
Console.WriteLine()
' Find all books under $10.00.
results = Books.FindAll(AddressOf FindUnderTen)
If results.Count <> 0 Then
DisplayResults(results, "Books under $10:")
Else
Console.WriteLine(vbCrLf & "No books found.")
End If
Console.WriteLine()
' Find index values.
Console.WriteLine()
Dim ndx As Integer = Books.FindIndex(AddressOf FindComputer)
Console.WriteLine("Index of first computer book: " & ndx)
ndx = Books.FindLastIndex(AddressOf FindComputer)
Console.WriteLine("Index of last computer book: " & ndx)
Dim mid As Integer = Books.Count / 2
ndx = Books.FindIndex(mid, mid, AddressOf FindComputer)
Console.WriteLine("Index of first computer book in the second half of the collection: " & ndx)
ndx = Books.FindLastIndex(Books.Count - 1, mid, AddressOf FindComputer)
Console.WriteLine("Index of last computer book in the second half of the collection: " & ndx)
End Sub
Private Sub FillList()
' Create XML elements from a source file.
Dim xTree As XElement = XElement.Load("c:\temp\books.xml")
' Create an enumerable collection of the elements.
Dim elements As IEnumerable(Of XElement) = xTree.Elements
' Evaluate each element and set values in the book object.
For Each el As XElement In elements
Dim Book As New Book()
Book.ID = el.Attribute("id").Value
Dim props As IEnumerable(Of XElement) = el.Elements
For Each p As XElement In props
If p.Name.ToString.ToLower = "author" Then
Book.Author = p.Value
End If
If p.Name.ToString.ToLower = "title" Then
Book.Title = p.Value
End If
If p.Name.ToString.ToLower = "genre" Then
Book.Genre = p.Value
End If
If p.Name.ToString.ToLower = "price" Then
Book.Price = Convert.ToDouble(p.Value)
End If
If p.Name.ToString.ToLower = "publish_date" Then
Book.Publish_date = Convert.ToDateTime(p.Value)
End If
If p.Name.ToString.ToLower = "description" Then
Book.Description = p.Value
End If
Next
Books.Add(Book)
Next
DisplayResults(Books, "All books:")
Console.WriteLine()
End Sub
' Predicate delegates for
' Find and FindAll methods.
Private Function FindID(ByVal bk As Book) As Boolean
If bk.ID = IDToFind Then
Return True
Else
Return False
End If
End Function
Private Function FindComputer(ByVal bk As Book) As Boolean
If bk.Genre = "Computer" Then
Return True
Else
Return False
End If
End Function
Private Function FindUnderTen(ByVal bk As Book) As Boolean
Dim tendollars As Double = 10.0
If bk.Price < tendollars Then
Return True
Else
Return False
End If
End Function
Private Function PubBefore2001(ByVal bk As Book) As Boolean
Dim year2001 As DateTime = New DateTime(2001, 1, 1)
Return bk.Publish_date < year2001
End Function
Private Sub DisplayResult(ByVal result As Book, ByVal title As String)
Console.WriteLine()
Console.WriteLine(title)
Console.WriteLine(vbLf & result.ID & vbTab & result.Author & _
vbTab & result.Title & vbTab & result.Genre & _
vbTab & result.Publish_date & vbTab & result.Price)
Console.WriteLine()
End Sub
Private Sub DisplayResults(ByVal results As List(Of Book), ByVal title As String)
Console.WriteLine()
Console.WriteLine(title)
For Each b As Book In results
Console.Write(vbLf & b.ID & vbTab & b.Author & _
vbTab & b.Title & vbTab & b.Genre & _
vbTab & b.Publish_date & vbTab & b.Price)
Next
Console.WriteLine()
End Sub
Public Class Book
Public ID As String
Public Author As String
Public Title As String
Public Genre As String
Public Price As Double
Public Publish_date As DateTime
Public Description As String
End Class
End Module
Remarques
La List<T> recherche est effectuée vers l’arrière à partir du dernier élément et se termine au premier élément.
Il Predicate<T> s’agit d’un délégué à une méthode qui retourne true si l’objet passé à celui-ci correspond aux conditions définies dans le délégué. Les éléments du courant List<T> sont transmis individuellement au Predicate<T> délégué.
Cette méthode effectue une recherche linéaire ; par conséquent, cette méthode est une opération O(n), où n est Count.
Voir aussi
- Exists(Predicate<T>)
- Find(Predicate<T>)
- FindLast(Predicate<T>)
- FindAll(Predicate<T>)
- FindIndex
- BinarySearch
- IndexOf
- LastIndexOf
- Predicate<T>
S’applique à
FindLastIndex(Int32, Predicate<T>)
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans la plage d’éléments de l’élément List<T> qui s’étend du premier élément à l’index spécifié.
public:
int FindLastIndex(int startIndex, Predicate<T> ^ match);
public int FindLastIndex(int startIndex, Predicate<T> match);
member this.FindLastIndex : int * Predicate<'T> -> int
Public Function FindLastIndex (startIndex As Integer, match As Predicate(Of T)) As Integer
Paramètres
- startIndex
- Int32
Index de départ de base zéro de la recherche descendante.
- match
- Predicate<T>
Délégué Predicate<T> qui définit les conditions de l’élément à rechercher.
Retours
Index de base zéro de la dernière occurrence d’un élément qui correspond aux conditions définies par match, s’il est trouvé ; sinon, -1.
Exceptions
match a la valeur null.
startIndex est en dehors de la plage d’index valides pour le List<T>.
Remarques
L’objet List<T> est recherché à l’arrière à startIndex partir et se termine au premier élément.
Il Predicate<T> s’agit d’un délégué à une méthode qui retourne true si l’objet passé à celui-ci correspond aux conditions définies dans le délégué. Les éléments du courant List<T> sont transmis individuellement au Predicate<T> délégué.
Cette méthode effectue une recherche linéaire ; par conséquent, cette méthode est une opération O(n), où n est le nombre d’éléments du début de la valeur List<T>startIndex.
Voir aussi
- Exists(Predicate<T>)
- Find(Predicate<T>)
- FindLast(Predicate<T>)
- FindAll(Predicate<T>)
- FindIndex
- BinarySearch
- IndexOf
- LastIndexOf
- Predicate<T>
S’applique à
FindLastIndex(Int32, Int32, Predicate<T>)
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
- Source:
- List.cs
Recherche un élément qui correspond aux conditions définies par le prédicat spécifié et retourne l’index de base zéro de la dernière occurrence dans la plage d’éléments dans la List<T> plage d’éléments qui contient le nombre spécifié d’éléments et se termine à l’index spécifié.
public:
int FindLastIndex(int startIndex, int count, Predicate<T> ^ match);
public int FindLastIndex(int startIndex, int count, Predicate<T> match);
member this.FindLastIndex : int * int * Predicate<'T> -> int
Public Function FindLastIndex (startIndex As Integer, count As Integer, match As Predicate(Of T)) As Integer
Paramètres
- startIndex
- Int32
Index de départ de base zéro de la recherche descendante.
- count
- Int32
Nombre d’éléments de la section à rechercher.
- match
- Predicate<T>
Délégué Predicate<T> qui définit les conditions de l’élément à rechercher.
Retours
Index de base zéro de la dernière occurrence d’un élément qui correspond aux conditions définies par match, s’il est trouvé ; sinon, -1.
Exceptions
match a la valeur null.
startIndex est en dehors de la plage d’index valides pour le List<T>.
- ou -
count est inférieur à 0.
- ou -
startIndex et count ne spécifiez pas de section valide dans le List<T>.
Exemples
L’exemple suivant illustre les méthodes de recherche pour la List<T> classe. L’exemple de la List<T> classe contient des book objets, de classe Book, à l’aide des données de l’exemple de fichier XML : Books (LINQ to XML). La FillList méthode de l’exemple utilise LINQ to XML pour analyser les valeurs du code XML aux valeurs de propriété des book objets.
Le tableau suivant décrit les exemples fournis pour les méthodes de recherche.
| Méthode | Example |
|---|---|
| Find(Predicate<T>) | Recherche un livre par ID à l’aide du IDToFind délégué de prédicat.L’exemple C# utilise un délégué anonyme. |
| FindAll(Predicate<T>) | Recherchez tous les livres dont Genre la propriété est « Computer » à l’aide du FindComputer délégué de prédicat. |
| FindLast(Predicate<T>) | Recherche le dernier livre de la collection dont la date de publication est antérieure à 2001, à l’aide du PubBefore2001 délégué de prédicat.L’exemple C# utilise un délégué anonyme. |
| FindIndex(Predicate<T>) | Recherche l’index du premier carnet d’ordinateurs à l’aide du FindComputer délégué de prédicat. |
| FindLastIndex(Predicate<T>) | Recherche l’index du dernier carnet d’ordinateurs à l’aide du FindComputer délégué de prédicat. |
| FindIndex(Int32, Int32, Predicate<T>) | Recherche l’index du premier carnet d’ordinateurs dans la deuxième moitié de la collection, à l’aide du FindComputer délégué de prédicat. |
| FindLastIndex(Int32, Int32, Predicate<T>) | Recherche l’index du dernier livre informatique dans la deuxième moitié de la collection, à l’aide du FindComputer délégué de prédicat. |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Find
{
class Program
{
private static string IDtoFind = "bk109";
private static List<Book> Books = new List<Book>();
public static void Main(string[] args)
{
FillList();
// Find a book by its ID.
Book result = Books.Find(
delegate(Book bk)
{
return bk.ID == IDtoFind;
}
);
if (result != null)
{
DisplayResult(result, "Find by ID: " + IDtoFind);
}
else
{
Console.WriteLine("\nNot found: {0}", IDtoFind);
}
// Find last book in collection published before 2001.
result = Books.FindLast(
delegate(Book bk)
{
DateTime year2001 = new DateTime(2001,01,01);
return bk.Publish_date < year2001;
});
if (result != null)
{
DisplayResult(result, "Last book in collection published before 2001:");
}
else
{
Console.WriteLine("\nNot found: {0}", IDtoFind);
}
// Find all computer books.
List<Book> results = Books.FindAll(FindComputer);
if (results.Count != 0)
{
DisplayResults(results, "All computer:");
}
else
{
Console.WriteLine("\nNo books found.");
}
// Find all books under $10.00.
results = Books.FindAll(
delegate(Book bk)
{
return bk.Price < 10.00;
}
);
if (results.Count != 0)
{
DisplayResults(results, "Books under $10:");
}
else
{
Console.WriteLine("\nNo books found.");
}
// Find index values.
Console.WriteLine();
int ndx = Books.FindIndex(FindComputer);
Console.WriteLine("Index of first computer book: {0}", ndx);
ndx = Books.FindLastIndex(FindComputer);
Console.WriteLine("Index of last computer book: {0}", ndx);
int mid = Books.Count / 2;
ndx = Books.FindIndex(mid, mid, FindComputer);
Console.WriteLine("Index of first computer book in the second half of the collection: {0}", ndx);
ndx = Books.FindLastIndex(Books.Count - 1, mid, FindComputer);
Console.WriteLine("Index of last computer book in the second half of the collection: {0}", ndx);
}
// Populates the list with sample data.
private static void FillList()
{
// Create XML elements from a source file.
XElement xTree = XElement.Load(@"c:\temp\books.xml");
// Create an enumerable collection of the elements.
IEnumerable<XElement> elements = xTree.Elements();
// Evaluate each element and set set values in the book object.
foreach (XElement el in elements)
{
Book book = new Book();
book.ID = el.Attribute("id").Value;
IEnumerable<XElement> props = el.Elements();
foreach (XElement p in props)
{
if (p.Name.ToString().ToLower() == "author")
{
book.Author = p.Value;
}
else if (p.Name.ToString().ToLower() == "title")
{
book.Title = p.Value;
}
else if (p.Name.ToString().ToLower() == "genre")
{
book.Genre = p.Value;
}
else if (p.Name.ToString().ToLower() == "price")
{
book.Price = Convert.ToDouble(p.Value);
}
else if (p.Name.ToString().ToLower() == "publish_date")
{
book.Publish_date = Convert.ToDateTime(p.Value);
}
else if (p.Name.ToString().ToLower() == "description")
{
book.Description = p.Value;
}
}
Books.Add(book);
}
DisplayResults(Books, "All books:");
}
// Explicit predicate delegate.
private static bool FindComputer(Book bk)
{
if (bk.Genre == "Computer")
{
return true;
}
else
{
return false;
}
}
private static void DisplayResult(Book result, string title)
{
Console.WriteLine();
Console.WriteLine(title);
Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", result.ID,
result.Author, result.Title, result.Genre, result.Price,
result.Publish_date.ToShortDateString());
Console.WriteLine();
}
private static void DisplayResults(List<Book> results, string title)
{
Console.WriteLine();
Console.WriteLine(title);
foreach (Book b in results)
{
Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", b.ID,
b.Author, b.Title, b.Genre, b.Price,
b.Publish_date.ToShortDateString());
}
Console.WriteLine();
}
}
public class Book
{
public string ID { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public double Price { get; set; }
public DateTime Publish_date { get; set; }
public string Description { get; set; }
}
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1
Private IDToFind As String = "bk109"
Public Books As New List(Of Book)
Sub Main()
FillList()
' Find a book by its ID.
Dim result As Book = Books.Find(AddressOf FindID)
If result IsNot Nothing Then
DisplayResult(result, "Find by ID: " & IDToFind)
Else
Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
End If
Console.WriteLine()
' Find last book in collection that has a publish date before 2001.
result = Books.FindLast(AddressOf PubBefore2001)
If result IsNot Nothing Then
DisplayResult(result, "Last book in collection published before 2001:")
Else
Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
End If
Console.WriteLine()
' Find all computer books.
Dim results As List(Of Book) = Books.FindAll(AddressOf FindComputer)
If results.Count <> 0 Then
DisplayResults(results, "All computer books:")
Else
Console.WriteLine(vbCrLf & "No books found.")
End If
Console.WriteLine()
' Find all books under $10.00.
results = Books.FindAll(AddressOf FindUnderTen)
If results.Count <> 0 Then
DisplayResults(results, "Books under $10:")
Else
Console.WriteLine(vbCrLf & "No books found.")
End If
Console.WriteLine()
' Find index values.
Console.WriteLine()
Dim ndx As Integer = Books.FindIndex(AddressOf FindComputer)
Console.WriteLine("Index of first computer book: " & ndx)
ndx = Books.FindLastIndex(AddressOf FindComputer)
Console.WriteLine("Index of last computer book: " & ndx)
Dim mid As Integer = Books.Count / 2
ndx = Books.FindIndex(mid, mid, AddressOf FindComputer)
Console.WriteLine("Index of first computer book in the second half of the collection: " & ndx)
ndx = Books.FindLastIndex(Books.Count - 1, mid, AddressOf FindComputer)
Console.WriteLine("Index of last computer book in the second half of the collection: " & ndx)
End Sub
Private Sub FillList()
' Create XML elements from a source file.
Dim xTree As XElement = XElement.Load("c:\temp\books.xml")
' Create an enumerable collection of the elements.
Dim elements As IEnumerable(Of XElement) = xTree.Elements
' Evaluate each element and set values in the book object.
For Each el As XElement In elements
Dim Book As New Book()
Book.ID = el.Attribute("id").Value
Dim props As IEnumerable(Of XElement) = el.Elements
For Each p As XElement In props
If p.Name.ToString.ToLower = "author" Then
Book.Author = p.Value
End If
If p.Name.ToString.ToLower = "title" Then
Book.Title = p.Value
End If
If p.Name.ToString.ToLower = "genre" Then
Book.Genre = p.Value
End If
If p.Name.ToString.ToLower = "price" Then
Book.Price = Convert.ToDouble(p.Value)
End If
If p.Name.ToString.ToLower = "publish_date" Then
Book.Publish_date = Convert.ToDateTime(p.Value)
End If
If p.Name.ToString.ToLower = "description" Then
Book.Description = p.Value
End If
Next
Books.Add(Book)
Next
DisplayResults(Books, "All books:")
Console.WriteLine()
End Sub
' Predicate delegates for
' Find and FindAll methods.
Private Function FindID(ByVal bk As Book) As Boolean
If bk.ID = IDToFind Then
Return True
Else
Return False
End If
End Function
Private Function FindComputer(ByVal bk As Book) As Boolean
If bk.Genre = "Computer" Then
Return True
Else
Return False
End If
End Function
Private Function FindUnderTen(ByVal bk As Book) As Boolean
Dim tendollars As Double = 10.0
If bk.Price < tendollars Then
Return True
Else
Return False
End If
End Function
Private Function PubBefore2001(ByVal bk As Book) As Boolean
Dim year2001 As DateTime = New DateTime(2001, 1, 1)
Return bk.Publish_date < year2001
End Function
Private Sub DisplayResult(ByVal result As Book, ByVal title As String)
Console.WriteLine()
Console.WriteLine(title)
Console.WriteLine(vbLf & result.ID & vbTab & result.Author & _
vbTab & result.Title & vbTab & result.Genre & _
vbTab & result.Publish_date & vbTab & result.Price)
Console.WriteLine()
End Sub
Private Sub DisplayResults(ByVal results As List(Of Book), ByVal title As String)
Console.WriteLine()
Console.WriteLine(title)
For Each b As Book In results
Console.Write(vbLf & b.ID & vbTab & b.Author & _
vbTab & b.Title & vbTab & b.Genre & _
vbTab & b.Publish_date & vbTab & b.Price)
Next
Console.WriteLine()
End Sub
Public Class Book
Public ID As String
Public Author As String
Public Title As String
Public Genre As String
Public Price As Double
Public Publish_date As DateTime
Public Description As String
End Class
End Module
Remarques
La List<T> recherche est effectuée vers l’arrière à startIndex partir et se terminant à startIndex moins count 1, si count elle est supérieure à 0.
Il Predicate<T> s’agit d’un délégué à une méthode qui retourne true si l’objet passé à celui-ci correspond aux conditions définies dans le délégué. Les éléments du courant List<T> sont transmis individuellement au Predicate<T> délégué.
Cette méthode effectue une recherche linéaire ; par conséquent, cette méthode est une opération O(n), où n est count.
Voir aussi
- Exists(Predicate<T>)
- Find(Predicate<T>)
- FindLast(Predicate<T>)
- FindAll(Predicate<T>)
- FindIndex
- BinarySearch
- IndexOf
- LastIndexOf
- Predicate<T>