Home >Backend Development >C#.Net Tutorial >C# Basic Operation Optimization Example Tutorial

C# Basic Operation Optimization Example Tutorial

零下一度
零下一度Original
2017-06-24 09:56:211629browse

Basic operations such as querying and deleting data are the basis of any programming language. Therefore, I studied the more commonly used types of data operations in C# and took notes.

List Query When processing relatively large data, use the HashSet class, because List is based on linear table operations. However, it has a binary search (BinarySearch) embedded in it. Therefore, you can also sort it after storing it, and then use binary search Search. But it can also be designed like this: Dictionary> Use Dictionary's efficient search query capability to search for List objects. But the data is stored using List.

HashSet is a collection class that does not contain repeated types. This collection is based on hash values, and its operations are very fast. Compared with HashTable, this collection class only contains one type parameter and is not based on keys. Value pairs are used to store the search elements. If you need to determine whether the element exists, you only need to call the Contains() method.
List search complexity O(n), HashSet search complexity O (1)

Delete and add operations of the Dictionary class:
By default, when not sorted, the position of the added element is at the position of the deleted element.
If sorted, the position of the added element will still be the position of the element before unsorting .

static void Main(string[] args)
        {
            Dictionary<int, int> _dic = new Dictionary<int, int>();

            _dic.Add(3, 3);
            _dic.Add(1, 1);
            _dic.Add(2, 2);
            _dic.Add(6, 6);

            Console.WriteLine("未经排序:");foreach (var k in _dic)
            {
                Console.WriteLine(k.Key + "   " + k.Value);
            }var dic_sort = from dic in _dic orderby dic.Key select dic;
            Console.WriteLine("未经处理:");foreach (var k in dic_sort)
            {
                Console.WriteLine(k.Key + "   " + k.Value);
            }

            Console.WriteLine("经过删除添加处理:");
            _dic.Remove(2);
            _dic.Add(4, 4);foreach (var k in _dic)
            {
                Console.WriteLine(k.Key + "   " + k.Value);
            }

            Console.Read();
        }

You can also test it yourself...

The above is the detailed content of C# Basic Operation Optimization Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn