android list命名空间,List

本文档介绍了.NET Framework中List<T>类的Contains和Exists方法,用于检查列表中是否存在特定元素。Contains方法利用IEquatable接口的Equals方法进行比较,而Exists方法则使用提供的委托判断条件。示例展示了如何在自定义对象列表中查找元素,包括基于属性的匹配。此外,还展示了如何在复杂对象列表中应用这些方法,以检查集合中是否存在具有相同属性的元素。
摘要由CSDN通过智能技术生成

确定某元素是否在 List 中。Determines whether an element is in the List.

public:

virtual bool Contains(T item);

public bool Contains (T item);

abstract member Contains : 'T -> bool

override this.Contains : 'T -> bool

Public Function Contains (item As T) As Boolean

参数

item

T

要在 List 中定位的对象。The object to locate in the List. 对于引用类型,该值可以为 null。The value can be null for reference types.

返回

如果在 true 中找到 item,则为 List;否则为 false。true if item is found in the List; otherwise, false.

实现

示例

下面的示例演示了的 Contains 和 Exists 方法 List ,其中包含实现的简单业务对象 Equals 。The following example demonstrates the Contains and Exists methods on a List that contains a simple business object that implements Equals.

using System;

using System.Collections.Generic;

// Simple business object. A PartId is used to identify a part

// but the part name can change.

public class Part : IEquatable

{

public string PartName { get; set; }

public int PartId { get; set; }

public override string ToString()

{

return "ID: " + PartId + " Name: " + PartName;

}

public override bool Equals(object obj)

{

if (obj == null) return false;

Part objAsPart = obj as Part;

if (objAsPart == null) return false;

else return Equals(objAsPart);

}

public override int GetHashCode()

{

return PartId;

}

public bool Equals(Part other)

{

if (other == null) return false;

return (this.PartId.Equals(other.PartId));

}

// Should also override == and != operators.

}

public class Example

{

public static void Main()

{

// Create a list of parts.

List parts = new List();

// Add parts to the list.

parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });

parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });

parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });

parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });

parts.Add(new Part() { PartName = "cassette", PartId = 1534 });

parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

// Write out the parts in the list. This will call the overridden ToString method

// in the Part class.

Console.WriteLine();

foreach (Part aPart in parts)

{

Console.WriteLine(aPart);

}

// Check the list for part #1734. This calls the IEquatable.Equals method

// of the Part class, which checks the PartId for equality.

Console.WriteLine("\nContains: Part with Id=1734: {0}",

parts.Contains(new Part { PartId = 1734, PartName = "" }));

// Find items where name contains "seat".

Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",

parts.Find(x => x.PartName.Contains("seat")));

// Check if an item with Id 1444 exists.

Console.WriteLine("\nExists: Part with Id=1444: {0}",

parts.Exists(x => x.PartId == 1444));

/*This code example produces the following output:

ID: 1234 Name: crank arm

ID: 1334 Name: chain ring

ID: 1434 Name: regular seat

ID: 1444 Name: banana seat

ID: 1534 Name: cassette

ID: 1634 Name: shift lever

Contains: Part with Id=1734: False

Find: Part where name contains "seat": ID: 1434 Name: regular seat

Exists: Part with Id=1444: True

*/

}

}

Imports System.Collections.Generic

' Simple business object. A PartId is used to identify a part

' but the part name can change.

Public Class Part

Implements IEquatable(Of Part)

Public Property PartName() As String

Get

Return m_PartName

End Get

Set(value As String)

m_PartName = Value

End Set

End Property

Private m_PartName As String

Public Property PartId() As Integer

Get

Return m_PartId

End Get

Set(value As Integer)

m_PartId = Value

End Set

End Property

Private m_PartId As Integer

Public Overrides Function ToString() As String

Return Convert.ToString("ID: " & PartId & " Name: ") & PartName

End Function

Public Overrides Function Equals(obj As Object) As Boolean

If obj Is Nothing Then

Return False

End If

Dim objAsPart As Part = TryCast(obj, Part)

If objAsPart Is Nothing Then

Return False

Else

Return Equals(objAsPart)

End If

End Function

Public Overrides Function GetHashCode() As Integer

Return PartId

End Function

Public Overloads Function Equals(other As Part) As Boolean _

Implements IEquatable(Of Part).Equals

If other Is Nothing Then

Return False

End If

Return (Me.PartId.Equals(other.PartId))

End Function

' Should also override == and != operators.

End Class

Public Class Example

Public Shared Sub Main()

' Create a list of parts.

Dim parts As New List(Of Part)()

' Add parts to the list.

parts.Add(New Part() With { _

.PartName = "crank arm", _

.PartId = 1234 _

})

parts.Add(New Part() With { _

.PartName = "chain ring", _

.PartId = 1334 _

})

parts.Add(New Part() With { _

.PartName = "regular seat", _

.PartId = 1434 _

})

parts.Add(New Part() With { _

.PartName = "banana seat", _

.PartId = 1444 _

})

parts.Add(New Part() With { _

.PartName = "cassette", _

.PartId = 1534 _

})

parts.Add(New Part() With { _

.PartName = "shift lever", _

.PartId = 1634 _

})

' Write out the parts in the list. This will call the overridden ToString method

' in the Part class.

Console.WriteLine()

For Each aPart As Part In parts

Console.WriteLine(aPart)

Next

' Check the list for part #1734. This calls the IEquatable.Equals method

' of the Part class, which checks the PartId for equality.

Console.WriteLine(vbLf & "Contains: Part with Id=1734: {0}",

parts.Contains(New Part() With { _

.PartId = 1734, _

.PartName = "" _

}))

' Find items where name contains "seat".

Console.WriteLine(vbLf & "Find: Part where name contains ""seat"": {0}",

parts.Find(Function(x) x.PartName.Contains("seat")))

' Check if an item with Id 1444 exists.

Console.WriteLine(vbLf & "Exists: Part with Id=1444: {0}",

parts.Exists(Function(x) x.PartId = 1444))

'This code example produces the following output:

'

' ID: 1234 Name: crank arm

' ID: 1334 Name: chain ring

' ID: 1434 Name: regular seat

' ID: 1444 Name: banana seat

' ID: 1534 Name: cassette

' ID: 1634 Name: shift lever

'

' Contains: Part with Id=1734: False

'

' Find: Part where name contains "seat": ID: 1434 Name: regular seat

'

' Exists: Part with Id=1444: True

'

End Sub

End Class

下面的示例包含类型为的复杂对象的列表 Cube 。The following example contains a list of complex objects of type Cube. Cube类实现方法, IEquatable.Equals 以便两个多维数据集的维度相同时被视为相等。The Cube class implements the IEquatable.Equals method so that two cubes are considered equal if their dimensions are the same. 在此示例中, Contains 方法返回 true ,因为集合中已存在具有指定维度的多维数据集。In this example, the Contains method returns true, because a cube that has the specified dimensions is already in the collection.

using System;

using System.Collections.Generic;

class Program

{

static void Main(string[] args)

{

List cubes = new List();

cubes.Add(new Cube(8, 8, 4));

cubes.Add(new Cube(8, 4, 8));

cubes.Add(new Cube(8, 6, 4));

if (cubes.Contains(new Cube(8, 6, 4))) {

Console.WriteLine("An equal cube is already in the collection.");

}

else {

Console.WriteLine("Cube can be added.");

}

//Outputs "An equal cube is already in the collection."

}

}

public class Cube : IEquatable

{

public Cube(int h, int l, int w)

{

this.Height = h;

this.Length = l;

this.Width = w;

}

public int Height { get; set; }

public int Length { get; set; }

public int Width { get; set; }

public bool Equals(Cube other)

{

if (this.Height == other.Height && this.Length == other.Length

&& this.Width == other.Width) {

return true;

}

else {

return false;

}

}

}

Imports System.Collections.Generic

Class Program

Public Shared Sub Main(ByVal args As String())

Dim cubes As New List(Of Cube)()

cubes.Add(New Cube(8, 8, 4))

cubes.Add(New Cube(8, 4, 8))

cubes.Add(New Cube(8, 6, 4))

If cubes.Contains(New Cube(8, 6, 4)) Then

Console.WriteLine("An equal cube is already in the collection.")

Else

Console.WriteLine("Cube can be added.")

End If

'Outputs "An equal cube is already in the collection."

End Sub

End Class

Public Class Cube

Implements IEquatable(Of Cube)

Public Sub New(ByVal h As Integer, ByVal l As Integer, ByVal w As Integer)

Me.Height = h

Me.Length = l

Me.Width = w

End Sub

Private _Height As Integer

Public Property Height() As Integer

Get

Return _Height

End Get

Set(ByVal value As Integer)

_Height = value

End Set

End Property

Private _Length As Integer

Public Property Length() As Integer

Get

Return _Length

End Get

Set(ByVal value As Integer)

_Length = value

End Set

End Property

Private _Width As Integer

Public Property Width() As Integer

Get

Return _Width

End Get

Set(ByVal value As Integer)

_Width = value

End Set

End Property

Public Overloads Function Equals(ByVal other As Cube) _

As Boolean Implements IEquatable(Of Cube).Equals

If Me.Height = other.Height And Me.Length = other.Length _

And Me.Width = other.Width Then

Return True

Else

Return False

End If

End Function

End Class

注解

此方法通过使用默认的相等比较器来确定相等性,如对象实现的方法所定义的 IEquatable.Equals T (列表) 中值的类型。This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).

此方法执行线性搜索;因此,此方法是 O (n) 操作,其中 n 是 Count 。This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

适用于

另请参阅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值