0% found this document useful (0 votes)
22 views9 pages

Lists and LINQ

Lists in C# allow storing collections of elements without a fixed size limit like arrays. Generic collections like List<T> can be defined to store any type. The Count property tracks the number of elements in a list. LINQ provides query capabilities to select, filter, and project data from lists and other collections. Key LINQ operators include Where for filtering, From to declare range variables over collections, and Select to determine query results.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views9 pages

Lists and LINQ

Lists in C# allow storing collections of elements without a fixed size limit like arrays. Generic collections like List<T> can be defined to store any type. The Count property tracks the number of elements in a list. LINQ provides query capabilities to select, filter, and project data from lists and other collections. Key LINQ operators include Where for filtering, From to declare range variables over collections, and Select to determine query results.

Uploaded by

cf8qrn9q4r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

19.01.

2024, 7:57 PM

Cheatsheets / Learn C#

Learn C#: Lists and LINQ

Lists in C#

In C#, a list is a generic data structure that can List<string> names = new List<string>
hold any type. Use the new operator and
();
declare the element type in the angle brackets
< >. List<Object> someObjects = new
In the example code, names is a list containing List<Object>();
string values. someObjects is a list
containing Object instances.

Generic Collections

Some collections, like lists and dictionaries, can using System.Collections.Generic;


be associated with various types. Instead of
defining a unique class for each possible type,
we define them with a generic type T , e.g. List<string> names = new List<string>
List<T> . ();
These collections are called generic collection
List<Object> objs = new List<Object>();
types. They are available in the
System.Collections.Generic Dictionary<string,int> scores = new
namespace. Dictionary<string, int>();
The generic type T will often show up in
documentation. When using a generic collection
in your code, the actual type is specified when
the collection is declared or instantiated.

about:srcdoc Page 1 of 9
19.01.2024, 7:57 PM

Limitless Lists

Unlike a C# array, a C# list does not have a // Initialize array with length 2
limited number of elements. You can add as
string[] citiesArray = new string[2];
many items as you like.
citiesArray[0] = "Los Angeles";
citiesArray[1] = "New York City";
citiesArray[2] = "Dubai"; // Error!

// Initialize list; no length needed


List<string> citiesList = new
List<string>();
citiesList.Add("Los Angeles");
citiesList.Add("New York City");
citiesList.Add("Dubai");

Count Property

The number of elements in a list is stored in the List<string> citiesList = new


Count property.
List<string>();
In the example code, the Count of
citiesList changes as we add and remove citiesList.Add("Los Angeles");
values. Console.WriteLine(citiesList.Count);
// Output: 1

citiesList.Add("New York City");


Console.WriteLine(citiesList.Count);
// Output: 2

citiesList.Remove("Los Angeles");
Console.WriteLine(citiesList.Count);
// Output: 1

about:srcdoc Page 2 of 9
19.01.2024, 7:57 PM

Contains()

In C#, the list method Contains() returns List<string> citiesList = new


true if its argument exists in the list;
List<string> { "Los Angeles", "New York
otherwise, false .
In the example code, the first call to City", "Dubai" };
Contains() returns true because “New
York City” is in the list. The second call returns result1 = citiesList.Contains("New York
false because “Cairo” is not in the list.
City");
// result1 is true

result2 = citiesList.Contains("Cairo");
// result2 is false

LINQ

LINQ is a set of language and framework


features for writing queries on collection types.
It is useful for selecting, accessing, and
transforming data in a dataset.

Using LINQ

LINQ features can be used in a C# program by using System.Linq;


importing the System.Linq namespace.

about:srcdoc Page 3 of 9
19.01.2024, 7:57 PM

var

Since the type of an executed LINQ query’s var custQuery = from cust in customers
result is not always known, it is common to store
where cust.City ==
the result in an implicitly typed variable using the
keyword var . "Phoenix"
select new { cust.Name,
cust.Phone };

Method & Query Syntax

In C#, LINQ queries can be written in method // Method syntax


syntax or query syntax.
var custQuery2 = customers.Where(cust
Method syntax resembles most other C# method
calls, while query syntax resembles SQL. => cust.City == "London");

// Query syntax
var custQuery =
from cust in customers
where cust.City == "London"
select cust;

about:srcdoc Page 4 of 9
19.01.2024, 7:57 PM

Where

In LINQ queries, the Where operator is used to List<Customer> customers = new


select certain elements from a sequence.
List<Customer>
It expects an expression that evaluates to
a boolean value. {
Every element satisfying the condition new Customer("Bartleby", "London"),
will be included in the resulting query.
new Customer("Benjamin",
It can be used in both method syntax and
query syntax. "Philadelphia"),
new Customer("Michelle", "Busan" )
};

// Query syntax
var custQuery =
from cust in customers
where cust.City == "London"
select cust;

// Method syntax
var custQuery2 = customers.Where(cust
=> cust.City == "London");

// Result: Customer("Bartleby",
"London")

about:srcdoc Page 5 of 9
19.01.2024, 7:57 PM

From

In LINQ queries, the from operator declares a string[] names = { "Hansel", "Gretel",
range variable that is used to traverse the
"Helga", "Gus" };
sequence. It is only used in query syntax.
In the example code, n represents each
element in names . The returned query only var query =
contains those elements for which
from n in names
n.Contains("a") is true.
where n.Contains("a")
select n;

// Result: Hansel, Helga

Select

In LINQ queries, the Select operator string[] trees = { "Elm", "Banyon",


determines what is returned for each element in
"Rubber" };
the resulting query. It can be used in both
method and query syntax.
// Query syntax
var treeQuery =
from t in trees
select t.ToUpper();

// Method syntax
var treeQuery2 = names.Select(t =>
t.ToUpper());

// Result: ELM, BANYON, RUBBER

about:srcdoc Page 6 of 9
19.01.2024, 7:57 PM

LINQ & foreach

You can use a foreach loop to iterate over string[] names = { "Hansel", "Gretel",
the result of an executed LINQ query.
"Helga", "Gus" };
In the example code, query is the result of a
LINQ query, and it can be iterated over using
foreach . name represents each element in var query = names.Where(n =>
names . n.Contains("a"));

foreach (var name in query)


{
Console.WriteLine(name);
}

Count()

The result of an executed LINQ query has a string[] names = { "Hansel", "Gretel",
method Count() , which returns the number
"Helga", "Gus" };
of elements it contains.
In the example code, Count() returns 2
because the resulting query contains 2 var query = names.Where(x =>
elements containing “a”.
x.Contains("a"));

Console.WriteLine(query.Count());
// Output: 2

Object Initialization

Values can be provided to a List when it is List<string> cities = new List<string>


constructed in a process called object
{ "Los Angeles", "New York City",
initialization.
Instead of parentheses, use curly braces after "Dubai" };
the list’s type.
Note that this can ONLY be used at the time of
construction.

about:srcdoc Page 7 of 9
19.01.2024, 7:57 PM

Remove()

Elements of a list can be removed with the List<string> citiesList = new


Remove() method. The method returns
List<string>();
true if the item is successfully removed;
otherwise, false . citiesList.Add("Los Angeles");
In the example code, attempting to remove citiesList.Add("New York City");
"Cairo" returns false because that citiesList.Add("Dubai");
element is not in the citiesList .

result1 = citiesList.Remove("New York


City");
// result1 is true

result2 = citiesList.Remove("Cairo");
// result2 is false

Clear()

All elements of a list can be removed with the List<string> citiesList = new
Clear() method. It returns nothing.
List<string> { "Delhi", "Los Angeles",
In the example code, the list is initialized with
three items. After calling Clear() , there are "Kiev" };
zero items in the list. citiesList.Clear();

Console.WriteLine(citiesList.Count);
// Output: 0

about:srcdoc Page 8 of 9
19.01.2024, 7:57 PM

List Ranges

Unlike elements in a C# array, multiple elements string[] african = new string[] {


of a C# list can be accessed, added, or removed
"Cairo", "Johannesburg" };
simultaneously. A group of multiple, sequential
elements within a list is called a range. string[] asian = new string[] {
Some common range-related methods are: "Delhi", "Seoul" };
AddRange()
List<string> citiesList = new
InsertRange()
RemoveRange() List<string>();

// Add two cities to the list


citiesList.AddRange(african);
// List: "Cairo", "Johannesburg"

// Add two cities to the front of the


list
citiesList.InsertRange(0, asian);
// List: "Delhi", "Seoul", "Cairo",
"Johannesburg"

// Remove the second and third cities


from the list
citiesList.RemoveRange(1, 2);
// List: "Delhi", "Johannesburg"

Print Share

about:srcdoc Page 9 of 9

You might also like