• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#中Find与FindAll用法的区别

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Entity entCurr = entCollection.Find(delegate(Entity m) { return m.name== "aa"; }); 对象
List<Entity> ltEntity= entCollection.FindAll(delegate(Entity m) { return m.name== "aa"; })

 

Arrays do not resize dynamically. The List type in the C# language does. With List, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. It provides many methods and properties.

Key points:Lists are considered generics and constructed types. You need to use < and > in the List declaration.

Add values

To start, we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size and add four prime numbers to it. The angle brackets are part of the declaration type—not conditional operators that mean less or more than. They are treated differently in the language.

Program that adds elements to List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<int> list = new List<int>();
	list.Add(2);
	list.Add(3);
	list.Add(5);
	list.Add(7);
    }
}

The above example shows how you can add a primitive type such as integer to a List collection. The List collection can also hold reference types and object instances.

Add

Note:There is more information on adding objects with the Add method on this site.

Loops

You can loop through your List with for and foreach loops. This is a common operation when using List. The syntax is the same as that for an array, except your use Count, not Length for the upper bound.

Backwards:You can also loop backwards through your List by reversing the for loop iteration variables. Start with list.Count - 1, and proceed decrementing to >= 0.

Program that loops through List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<int> list = new List<int>();
	list.Add(2);
	list.Add(3);
	list.Add(7);

	foreach (int prime in list) // Loop through List with foreach
	{
	    Console.WriteLine(prime);
	}

	for (int i = 0; i < list.Count; i++) // Loop through List with for
	{
	    Console.WriteLine(list[i]);
	}
    }
}

Output
    (Repeated twice)
2
3
7

Count

To get the number of elements in your List, access the Count property. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays. See the next section for an example on using the Count property.

Clear

Here we use the Clear method, along with the Count property, to erase all the elements in a List. Before Clear is called, this List has 3 elements. After Clear is called, it has 0 elements.

Alternatively:You can assign the List to null instead of calling Clear, with similar performance. After assigning to null, you must call the constructor again.

Program that counts List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<bool> list = new List<bool>();
	list.Add(true);
	list.Add(false);
	list.Add(true);
	Console.WriteLine(list.Count); // 3

	list.Clear();
	Console.WriteLine(list.Count); // 0
    }
}

Output

3
0

Copy array to List

Here we see an easy way to create a new List with the elements in an array that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.

Program that copies array to List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	int[] arr = new int[3]; // New array with 3 elements
	arr[0] = 2;
	arr[1] = 3;
	arr[2] = 5;
	List<int> list = new List<int>(arr); // Copy to List
	Console.WriteLine(list.Count);       // 3 elements in List
    }
}

Output
    (Indicates number of elements.)

3

It is useful to use the List constructor code here to create a new List from Dictionary keys. This will give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler will refuse to compile your code.

Find elements

You can test each element in your List for a certain value. This shows the foreach loop, which tests to see if 3 is in the List of prime numbers. Note that more advanced List methods are available to find matches in the List, but they often aren't any better than this loop. They can sometimes result in shorter code.

Find

Program that uses foreach on List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// New list for example
	List<int> primes = new List<int>(new int[] { 2, 3, 5 });

	// See if List contains 3
	foreach (int number in primes)
	{
	    if (number == 3) // Will match once
	    {
		Console.WriteLine("Contains 3");
	    }
	}
    }
}

Output

Contains 3

Capacity

You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. My research shows that capacity can improve performance by nearly two times for adding elements.

Capacity Property

Note:This is not usually a performance bottleneck in programs that access data.

TrimExcess method. There is the TrimExcess method on List as well, but its usage is limited. I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list is at more than 90 percent of capacity."

MSDN reference

BinarySearch

You can use the binary search algorithm on List with the instance BinarySearch method. Binary search uses guesses to find the correct element much faster than linear searching. It is often much slower than Dictionary.

BinarySearch List

AddRange and InsertRange

You can use AddRange and InsertRange to add or insert collections of elements into your existing List. This can make your code simpler. Please see an example of these methods on this site.

AddRange

ForEach

Sometimes you may not want to write a regular foreach loop, which makes ForEach useful. This accepts an Action, which is a void delegate method. Be cautious when you use Predicates and Actions—they can decrease the readability of your code.

The TrueForAll method accepts a Predicate. If the Predicate returns true for each element in your List, the TrueForAll method will return true also. Else, it will return false.

Join string List

Here we see how you can use string.Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List. The biggest advantage of Join here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.

Program that joins List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// List of cities we need to join
	List<string> cities = new List<string>();
	cities.Add("New York");
	cities.Add("Mumbai");
	cities.Add("Berlin");
	cities.Add("Istanbul");

	// Join strings into one CSV line
	string line = string.Join(",", cities.ToArray());
	Console.WriteLine(line);
    }
}

Output

New York,Mumbai,Berlin,Istanbul

Keys in Dictionary

You can use the List constructor to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection of keys, which can be passed to the List constructor as a parameter.

Program that converts Keys [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Populate example Dictionary
	var dict = new Dictionary<int, bool>();
	dict.Add(3, true);
	dict.Add(5, false);

	// Get a List of all the Keys
	List<int> keys = new List<int>(dict.Keys);
	foreach (int key in keys)
	{
	    Console.WriteLine(key);
	}
    }
}

Output

3, 5

Insert

You can insert an element into your List at any position. The string "dalmation" is inserted into index 1. This makes it become the second element in the List. If you have to Insert elements extensively, please consider the Queue and LinkedList collections for better performance.

Queue

Additionally:A Queue may provide clearer usage of the collection in your code.

Program that inserts into List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<string> dogs = new List<string>(); // Example List

	dogs.Add("spaniel");         // Contains: spaniel
	dogs.Add("beagle");          // Contains: spaniel, beagle
	dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle

	foreach (string dog in dogs) // Display for verification
	{
	    Console.WriteLine(dog);
	}
    }
}

Output

spaniel
dalmation
beagle

Remove

The removal methods on List are covered in depth in another article on this site. It contains examples for Remove, RemoveAt, RemoveAll and RemoveRange, along with my notes.

Remove

Sort

Sort orders the elements in the List. For strings it will order them alphabetically. For integers or other numbers it will order them from lowest to highest. It acts upon elements depending on their type. It is also possible to provide a custom comparison method.

Sort

Reverse

This example program uses Reverse on a List. The strings contained in the List are left unchanged. But the order they appear in the List is inverted. Afterwards we look inside the Reverse method.

Program that uses Reverse [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<string> list = new List<string>();
	list.Add("anchovy");
	list.Add("barracuda");
	list.Add("bass");
	list.Add("viperfish");

	// Reverse List in-place, no new variables required
	list.Reverse();

	foreach (string value in list)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

viperfish
bass
barracuda
anchovy

The List Reverse method, which internally uses the Array.Reverse method, provides an easy way to reverse the order of the elements in your List. It does not change the individual elements in any way.

Array.Reverse

List to array

You can convert your List to an array of the same type using the instance method ToArray. There are examples of this conversion, and the opposite, on this site.

List to ArrayCopyTo

Range of elements

You can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ. It has different syntax.

Program that gets ranges from List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<string> rivers = new List<string>(new string[]
	{
	    "nile",
	    "amazon",     // River 2
	    "yangtze",    // River 3
	    "mississippi",
	    "yellow"
	});

	// Get rivers 2 through 3
	List<string> range = rivers.GetRange(1, 2);
	foreach (string river in range)
	{
	    Console.WriteLine(river);
	}
    }
}

Output

amazon
yangtze

DataGridView

You can use the List type with a DataGridView collection in Windows Forms. Sometimes, though, it is better to convert your List to a DataTable. For a List of string arrays, this will make the DataGridView display the elements correctly.

Convert List to DataTable: DataGridView

Equality

Sometimes you may need to test two Lists for equality, even when their elements are unordered. You can do this by sorting both of them and then comparing, or by using a custom List equality method.

List Element Equality

Note:This site contains an example of a method that tests lists for equality in an unordered way.

Structs

When using List, you can improve performance and reduce memory usage with structs instead of classes. A List of structs is allocated in contiguous memory, unlike a List of classes. This is an advanced optimization.

In many cases:Using structs will actually decrease the performance when they are used as parameters in methods such as those on the List type.

Var

Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.

Program that uses var with List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
	var list1 = new List<int>();       // <- var keyword used
	List<int> list2 = new List<int>(); // <- Is equivalent to
    }
}

Summary

We saw lots of examples with the List constructed type. List is powerful and performs well. It provides flexible allocation and growth, making it much easier to use than arrays.

Therefore:In most programs that do not have memory or performance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.

 

http://www.dotnetperls.com/list

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
【C#】时间戳转换发布时间:2022-07-14
下一篇:
如何使用C#调用U8的COM组件之一前言发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap