Skip to content

Instantly share code, notes, and snippets.

@onlyforbopi
Last active October 18, 2021 15:47
Show Gist options
  • Save onlyforbopi/e706e09711c71377db29bbb6f35e8e81 to your computer and use it in GitHub Desktop.
Save onlyforbopi/e706e09711c71377db29bbb6f35e8e81 to your computer and use it in GitHub Desktop.
//Array elements can be accessed using an index. An index is a number associated with each array element, starting with index 0 and ending with array size - 1.
//The following example add/update and retrieve array elements using indexes.
//Example: Access Array Elements using Indexes
int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12; //Throws run-time exception IndexOutOfRange
Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4
*** Arrays ***
class MyApp
{
static void Main()
{
// Array declaration
int[] x; // not int x[]
// Array allocation
x = new int[3];
// Array assignment
x[0] = 1;
x[1] = 2;
x[2] = 3;
int[] y = new int[] { 1, 2, 3 };
int[] z = { 1, 2, 3 };
// Array access
System.Console.Write(x[0] + x[1] + x[2]); // "6"
// Rectangular arrays
string[,] a = new string[2, 2];
a[0, 0] = "00"; a[0, 1] = "01";
a[1, 0] = "10"; a[1, 1] = "11";
string[,] b = { { "00", "01" }, { "10", "11" } };
// Jagged arrays
string[][] c = new string[2][];
c[0] = new string[1]; c[0][0] = "00";
c[1] = new string[2]; c[1][0] = "10"; c[1][1] = "11";
string[][] d = { new string[] { "00", "01" },
new string[] { "10", "11" } };
}
}
// Declaration and Initialization
//An array can be declared using by specifying the type of its elements with square brackets.
//Example: Array Declaration
int[] evenNums; // integer array
string[] cities; // string array
//The following declares and adds values into an array in a single statement.
//Example: Array Declaration & Initialization
int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };
string[] cities = new string[3]{ "Mumbai", "London", "New York" };
//Above, evenNums array can store up to five integers. The number 5 in the square brackets new int[5] specifies the size of an array. In the same way, the size of cities array is three. Array elements are added in a comma-separated list inside curly braces { }.
//Arrays type variables can be declared using var without square brackets.
//Example: Array Declaration using var
var evenNums = new int[]{ 2, 4, 6, 8, 10};
var cities = new string[]{ "Mumbai", "London", "New York" };
//If you are adding array elements at the time of declaration, then size is optional. The compiler will infer its size based on the number of elements inside curly braces, as shown below.
//Example: Short Syntax of Array Declaration
int[] evenNums = { 2, 4, 6, 8, 10};
string[] cities = { "Mumbai", "London", "New York" }
//The following example demonstrate invalid array declarations.
//Example: Invalid Array Creation
//must specify the size
int[] evenNums = new int[];
//number of elements must be equal to the specified size
int[] evenNums = new int[5] { 2, 4 };
//cannot use var with array initializer
var evenNums = { 2, 4, 6, 8, 10};
//Late Initialization
//It is not necessary to declare and initialize an array in a single statement. You can first declare an array then initialize it later on using the new operator.
//Example: Late Initialization
int[] evenNums;
evenNums = new int[5];
// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };
//LINQ Methods
//All the arrays in C# are derived from an abstract base class System.Array.
//The Array class implements the IEnumerable interface, so you can LINQ extension methods such as Max(), Min(), Sum(), reverse(), etc. See the list of all extension methods here.
//Example: LINQ Methods
int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55
//The System.Array class also includes methods for creating, manipulating, searching, and sorting arrays. See list of all Array methods here.
//Example: Array Methods
int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
Array.Sort(nums); // sorts array
Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search
//Passing Array as Argument
//An array can be passed as an argument to a method parameter. Arrays are reference types, so the method can change the value of the array elements.
//Example: Passing Array as Argument
public static void Main(){
int[] nums = { 1, 2, 3, 4, 5 };
UpdateArray(nums);
foreach(var item in nums)
Console.WriteLine(item);
}
public static void UpdateArray(int[] arr)
{
for(int i = 0; i < arr.Length; i++)
arr[i] = arr[i] + 10;
}
//Searching in C# array
//C# By TutorialsTeacher 19 Mar 2020
//Often you need to search element(s) in an array based on some logic in C#. Use the Array.Find() or Array.FindAll() or Array.FindLast() methods to search for an elements that match with the specified condition.
Array.Find()
//The Array.Find() method searches for an element that matches the specified conditions using predicate delegate, and returns the first occurrence within the entire Array.
//Syntax:
public static T Find<T>(T[] array, Predicate<T> match);
//As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression. It returns the first element that satisfy the conditions defined by the predicate expression; otherwise, returns the default value for type T.
//The following example finds the first element that matches with string "Bill".
//Example: Find literal value Copy
string[] names = { "Steve", "Bill", "Bill Gates", "Ravi", "Mohan", "Salman", "Boski" };
var stringToFind = "Bill";
var result = Array.Find(names, element => element == stringToFind); // returns "Bill"
//The following example returns the first element that starts with "B".
//Example: Find elements that starts with B Copy
string[] names = { "Steve", "Bill", "Bill Gates", "James", "Mohan", "Salman", "Boski" };
var result = Array.Find(names, element => element.StartsWith("B")); // returns Bill
//The following example returns the first element, whose length is five or more.
//Example: Find by length Copy
string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
var result = Array.Find(names, element => element.Length >= 5); // returns Steve
//Notice that the Array.Find() method only returns the first occurrence and not all matching elements. Use the Array.FindAll() method to retrieve all matching elements.
Array.FindAll()
//The Array.FindAll() method returns all elements that match the specified condition.
Syntax:
public static T[] FindAll<T>(T[] array, Predicate<T> match)
//As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression. It returns all the elements that satisfy the condition defined by the predicate expression.
//The following example finds all elements that match with "Bill" or "bill".
//Example: Find literal values Copy
string[] names = { "Steve", "Bill", "bill", "James", "Mohan", "Salman", "Boski" };
var stringToFind = "bill";
string[] result = Array.FindAll(names, element => element.ToLower() == stringToFind); // return Bill, bill
//The following example finds all elements that start with B.
//Example: Find all elements starting with B Copy
string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
string[] result = Array.FindAll(names, element => element.StartsWith("B")); // return Bill, Boski
//The following example finds all elements whose length is five or more.
//Example: Find elements by length Copy
string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
string[] result = Array.FindAll(names, element => element.Length >= 5); // returns Steve, James, Mohan, Salman, Boski
//Array.FindLast()
//The Array.Find() method returns the first element that matches the condition. The Array.FindLast() method returns the last element that matches the specified condition in an array.
//Syntax:
public static T FindLast<T>(T[] array, Predicate<T> match)
//As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression. It returns the last element that satisfy the condition defined by the predicate expression. If not found then returns the default value for type T.
//The following example finds the last element that matches with "Bill".
//Example: Find last element Copy
string[] names = { "Steve", "Bill", "Bill Gates", "Ravi", "Mohan", "Salman", "Boski" };
var stringToFind = "Bill";
var result = Array.FindLast(names, element => element.Contains(stringToFind)); // returns "Boski"
//The following example returns the last element that starts with "B".
//Example: Find last element starting with B Copy
string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
var result = Array.FindLast(names, element => element.StartsWith("B")); // returns Boski
//The following example returns the first element, whose length is five or more.
//Example: Find last element by length Copy
string[] names = { "Steve", "Bill", "Bill Gates", "James", "Mohan", "Salman", "Boski" };
result = Array.FindLast(names, element => element.Length >= 5); // returns Boski
//Thus, choose the appropriate method as per your requirement to search for an element in an array in C#.
//How to sort an array in C#?
//C# By TutorialsTeacher 14 Jan 2020
//We can sort a one-dimensional array in two ways, using Array.Sort() method and using LINQ query.
Array.Sort()
//Array is the static helper class that includes all utility methods for all types of array in C#. The Array.Sort() method is used to sort an array in different ways.
//The following example sorts an array in ascending order.
//Example: Sort an Array Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
Array.Sort(animals); // Result: ["Alligator", "Bear", "Cat","Donkey","Elephant","Fox","Goat"]
//The following example sorts only the first three elements of an array.
//Example: Sort the Portion of Array Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
Array.Sort(animals, 0, 3); // Result: ["Alligator","Cat","Fox", "Donkey", "Bear", "Elephant", "Goat"]
//In the above example, we passed starting index 0 and length 3. So, it will sort three elements starting from index 0.
//The following example sorts two different arrays where one array contains keys, and another contains values.
//Example: Sort Keys and Values Copy
int[] numbers = { 2, 1, 4, 3 };
String[] numberNames = { "two", "one", "four", "three" };
Array.Sort(numbers, numberNames);
Array.ForEach<int>(numbers, n => Console.WriteLine(n));//[1,2,3,4]
Array.ForEach<string>(numberNames, s => Console.WriteLine(s));//["one", "two", "three", "four"]
//The Array.Reverse() method reverses the order of the elements in a one-dimensional Array or in a portion of the Array. Note that it does not sort an array in descending order but it reverses the order of existing elements.
//Example: Sort an Array in Descending Order Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
Array.Reverse(animals);// Result: ["Goat", "Fox", "Elephant", "Donkey", "Cat", "Bear", "Alligator"]
//Thus, the Array.Sort() method is easy to use and performs faster than LINQ queries.
//Sort an Array using LINQ
//An array can be sort using LINQ.
//Example: Sort an Array using LINQ Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Bear", "Elephant", "Goat" };
var sortedStr = from name in animals
orderby name
select name;
Array.ForEach<string>(sortedStr.ToArray<string>(), s => Console.WriteLine(s));
//You can sort an array in descending order easily.
//Example: Sort an Array using LINQ Copy
var sortedStr = from name in animals
orderby name descending
select name;
Array.ForEach<string>(sortedStr.ToArray<string>(), s => Console.WriteLine(s)); // Result: ["Goat", "Fox", "Elephant", "Donkey", "Cat", "Be"]
//How to count elements in C# array?
//C# By TutorialsTeacher 22 Jan 2020
//You can count the total number of elements or some specific elements in the array using an extension method Count() method.
//The Count() method is an extension method of IEnumerable included in System.Linq.Enumerable class. It can be used with any collection or a custom class that implements IEnumerable interface. All the built-in collections in C#, such as array, ArrayList, List, Dictionary, SortedList, etc. implements IEnumerable, and so the Count() method can be used with these collection types.
//Count() Overloads
//Count<TSource>() Returns total number of elements in an array.
//Count<TSource>(Func<TSource, Boolean>) Returns the total number of elements in an array that matches the specified condition using Func delegate.
//The following example displays the total number of elements in the array.
//Example: Count Array Elements Copy
string[] empty = new string[5];
var totalElements = empty.Count(); //5
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
totalElements = animals.Count(); //6
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2, 5, 6, 2, 2 };
totalElements = nums.Count(); //12
//In the above example, the empty.Count() returns 5, even if there are no elements in the array. This is because an array already has five null elements. For others, it will return the total number of elements.
//Count Specific Elements in an Array
//The following example shows how to count the specific elements based on some condition.
//Example: Count Specific Elements Copy
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
var totalCats = animals.Count(s => s == "Cat");
var animalsStartsWithA = animals1.Count(s => s.StartsWith("a", StringComparison.CurrentCultureIgnoreCase));
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2, 5, 6, 2, 2 };
var totalEvenNums = nums.Count(n => n%2==0);
//You can also use Regex with the Count() method, as shown below.
//Example: Regex with Count() Copy
string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
var animalsWithCapitalLetter = animals.Count(s =>
{
return Regex.IsMatch(s, "^[A-Z]");
});
//Accessing Array Elements
//Array elements can be accessed using an index. An index is a number associated with each array element, starting with index 0 and ending with array size - 1.
//The following example add/update and retrieve array elements using indexes.
//Example: Access Array Elements using Indexes
int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12; //Throws run-time exception IndexOutOfRange
Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4
//Note that trying to add more elements than its specified size will result in IndexOutOfRangeException.
//Accessing Array using for Loop
//Use the for loop to access array elements. Use the length property of an array in conditional expression of the for loop.
//Example: Accessing Array Elements using for Loop
int[] evenNums = { 2, 4, 6, 8, 10 };
for(int i = 0; i < evenNums.Length; i++)
Console.WriteLine(evenNums[i]);
for(int i = 0; i < evenNums.Length; i++)
evenNums[i] = evenNums[i] + 10; // update the value of each element by 10
//Accessing Array using foreach Loop
//Use foreach loop to read values of an array elements without using index.
//Example: Accessing Array using foreach Loop
int[] evenNums = { 2, 4, 6, 8, 10};
string[] cities = { "Mumbai", "London", "New York" };
foreach(var item in evenNums)
Console.WriteLine(item);
foreach(var city in cities)
Console.WriteLine(city);
//How to get a comma separated string from an array in C#?
//C# By TutorialsTeacher 15 Jan 2020
//We can get a comma-separated string from an array using String.Join() method.
//Example: String.Join() Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey" };
var str = String.Join(",", animals);
//In the same way, we can get a comma-separated string from the integer array.
//Example: String.Join() Copy
int[] nums = { 1, 2, 3, 4 };
var str = String.Join(",", nums);
//We can also get a comma separated string from the object array, as shown below.
//Example: String.Join() Copy
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Lary", LastName="Page"}
};
var str = String.Join(",", people.Select(p => p.FirstName) );
//How to combine two arrays without duplicate values in C#?
//C# By TutorialsTeacher 16 Jan 2020
//Learn how to combine two arrays without duplicate values in C# using the Union() method.
//Example: Combine String Arrays Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Cat" };
string[] birds = { "Sparrow", "Peacock", "Dove", "Crow" };
var all = animals.Union(birds).ToArray();
//In the same way, use the Union() method with the number array.
//Example: Copy
int[] num1 = { 1, 2, 3, 4, 3, 55, 23, 2 };
int[] num2 = { 55, 23, 45, 50, 80 };
var all = num1.Union(num2).ToArray();
//If an array contains objects of a custom class, then you need to implement IEquatable<T> or IEqualityComparer<T>, as shown below.
//Example: Implement IEquatable Copy
class Person : IEquatable<Person>
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Equals(Person other)
{
return FirstName.Equals(other.FirstName) && LastName.Equals(other.LastName);
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ (FirstName == null ? 0 : FirstName.GetHashCode()) ^ (LastName == null ? 0 : LastName.GetHashCode());
}
}
//Now, you can use the Union() method, as shown below.
//Example: Combine Object Arrays Copy
Person[] people1 = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Lary", LastName="Page"}
};
Person[] people2 = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Lary", LastName="Page"},
new Person(){ FirstName="Bill", LastName="Gates"}
};
var allp = people1.Union(people2).ToArray();
Array.ForEach(allp, p => Console.WriteLine(p.FirstName));
//How to remove duplicate values from an array in C#?
//C# By TutorialsTeacher 15 Jan 2020
//Removing duplicate values from an array in C# is essentially getting distinct values. In C#, we cannot remove values in the array. Instead, we will have to create a new array with the values we want. So, we have to get the distinct values from the specified array and create a new array of distinct values instead of removing duplicate values.
//The following example gets distinct values from an array using the Distinct() method and creates a new array.
//Example: Remove duplicate from integer array Copy
int[] nums = { 1, 2, 3, 4, 3, 55, 23, 2 };
int[] dist = nums.Distinct().ToArray();
//The same can be used with the string array.
//Example: Remove duplicate from string array Copy
string[] animals = { "Cat", "Alligator", "Fox", "Donkey", "Cat" };
string[] dist = animals.Distinct().ToArray();
//To remove duplicate values and get distinct values from an object array, we need to implement either IEquatable or IEqualityComparer.
//The following example gets a distinct array of the Person array.
//Example: Remove duplicate from object array Copy
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Lary", LastName="Page"}
};
var dist = people.Distinct(new PersonNameComparer()).ToArray();
//The following class implements IEqualityComparer<T> to be used with the Distinct() method.
//Example: IEqualityComparer<T> Copy
class PersonNameComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstName == y.FirstName && x.LastName == y.LastName;
}
public int GetHashCode(Person obj)
{
return obj.Id.GetHashCode() ^ (obj.FirstName == null ? 0 : obj.FirstName.GetHashCode()) ^ (obj.LastName == null ? 0 :obj.LastName.GetHashCode());
}
}
//In the above Equals() method, we compare FirstName and LastName. You may compare IDs also. It's upto you how you want to consider it equal.
//You may also implement IEquatable<T> in the Person class itself to get the same result.
//Example: IEquatable<T> Copy
class Person : IEquatable<Person>
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Equals(Person other)
{
return FirstName.Equals(other.FirstName) && LastName.Equals(other.LastName);
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ (FirstName == null ? 0 : FirstName.GetHashCode()) ^ (LastName == null ? 0 : LastName.GetHashCode());
}
}
//Now, we can get distinct persons without passing a parameter in the Distinct() method, as shown below.
//Example: Get distinct values from object array Copy
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Lary", LastName="Page"}
};
var dist = people.Distinct().ToArray();
//How to sort object array by specific property in C#?
//C# By TutorialsTeacher 14 Jan 2020
//Here, you will learn how to sort an array of objects by specific property in C#.
//There are two ways you can sort an object array by a specific property, using Array.Sort() method and by using LINQ query.
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Lary", LastName="Page"}
};
//The people array in the above example contains objects of Person class. You cannot use Array.Sort(people) because array contains objects, not primitive values.
//Now, let's sort the above people array by the LastName property. For that, you need to create a class and implement IComparer interface, as shown below.
//Example: Custom Comparer Class Copy
class PersonComparer : IComparer
{
public int Compare(object x, object y)
{
return (new CaseInsensitiveComparer()).Compare(((Person)x).LastName, ((Person)y).LastName);
}
}
//Now, we can sort an array using Array.Sort() method by specifying IComparer class.
//Example: Sort Object Array Copy
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Lary", LastName="Page"}
};
//Array.Sort(people, new PersonComparer());
//The same result can be achieved using LINQ query easily, as shown below.
//Example: Sort using LINQ Copy
Person[] people = {
new Person(){ FirstName="Steve", LastName="Jobs"},
new Person(){ FirstName="Bill", LastName="Gates"},
new Person(){ FirstName="Lary", LastName="Page"}
};
var qry = from p in list
orderby p.LastName
select p;
Array.ForEach<Person>(qry.ToArray<Person>(), p => Console.WriteLine(p.FirstName + " " + p.LastName));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment