Difference between find and findall in C #

Source: Internet
Author: User

Entity entcurr = entcollection. Find (delegate (entity m) {return M. Name = "AA" ;}); object
List <entity> ltentity = entcollection. findall (delegate (entity m) {return M. Name = "AA ";})

 

C # list

Arrays do not resize dynamically.ListType 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 initialize 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. 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 exampleShows 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 t 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)237
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); // 3list.Clear();Console.WriteLine(list.Count); // 0    }}Output30
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 Parameters es 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 elementsarr[0] = 2;arr[1] = 3;arr[2] = 5;List<int> list = new List<int>(arr); // Copy to ListConsole.WriteLine(list.Count);       // 3 elements in List    }}Output    (Indicates number of elements.)3

It is usefulTo 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 exampleList<int> primes = new List<int>(new int[] { 2, 3, 5 });// See if List contains 3foreach (int number in primes){    if (number == 3) // Will match once    {Console.WriteLine("Contains 3");    }}    }}OutputContains 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 uses CES the memory used. note: "The trimexcess method does nothing if the list is at more than 90 percent of capacity."

Msdn referencebinarysearch

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 listaddrange 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.

Addrangeforeach

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 MethodAccepts 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 wocould 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 joinList<string> cities = new List<string>();cities.Add("New York");cities.Add("Mumbai");cities.Add("Berlin");cities.Add("Istanbul");// Join strings into one CSV linestring line = string.Join(",", cities.ToArray());Console.WriteLine(line);    }}OutputNew 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 Dictionaryvar dict = new Dictionary<int, bool>();dict.Add(3, true);dict.Add(5, false);// Get a List of all the KeysList<int> keys = new List<int>(dict.Keys);foreach (int key in keys){    Console.WriteLine(key);}    }}Output3, 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 explain list 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 Listdogs.Add("spaniel");         // Contains: spanieldogs.Add("beagle");          // Contains: spaniel, beagledogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagleforeach (string dog in dogs) // Display for verification{    Console.WriteLine(dog);}    }}Outputspanieldalmationbeagle
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.

Removesort

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.

Sortreverse

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 requiredlist.Reverse();foreach (string value in list){    Console.WriteLine(value);}    }}Outputviperfishbassbarracudaanchovy

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. reverselist 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 arraycopytorange 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 3List<string> range = rivers.GetRange(1, 2);foreach (string river in range){    Console.WriteLine(river);}    }}Outputamazonyangtze
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: datagridviewequality

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 duplicate ity 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 container 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 usedList<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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.