CS Fundamentals v2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 97

INTRODUCTION TO

AND

C#

HELLO
C# defines one of the most powerful, feature-

rich languages in modern computing. C# is


intended to be a simple, modern, generalpurpose, object-oriented programming, static
language. C# is directly related to C, C++,
and Java.

Family Tree
C

C structured programming
C++ - first OO Model 1979
Java - portability 1992
- new and improved OO Model
Code translated into bytecode
and executed by JVM
Jav
Platform/CPU/OS independence a

C# - 2000

C+
+

C#

Why C#?
C# was created by Microsoft to fix some issues

caused by Java lacking some features and it was


part of Microsofts overall .NET strategy.
FULL INTEGRATION with the Windows platform.

(Java and Windows are not closely coupled and


Windows being the dominant desktop OS was a
serious issue for Java).
The other big issue is called mixed-language

programming. This is the ability for the code


produced by one language to work easily with the
code produced by another. This is essential when
building large distributed systems

Family Resemblance
From C, C# derives its syntax, many of its

keywords, and its operators. C# builds upon


and improves the object model defined by C+
+. If you know C or C++, then you will feel at
home with C#.
If you know Java, then many C# concepts will
be familiar. Conversely, if in the future you
need to learn Java, then many of the things
you learn about C# will carry over.

What is .NET ?
The .NET Framework defines an

environment that supports the


development and execution of
highly distributed, componentbased applications. It enables
differing computer languages to
work together and provides for
security, program portability,
and a common programming
model for the Windows platform.
It comes with Windows
(Windows 8 4.5, Windows 73.5, Vista- 2.0 and 3.0)or you
can download it from
http://www.microsoft.com/net/download

..NET Architecture

CLR manages your application


FCL a large library of functions, components

and technologies that you can use to build your


application.

.NET supports C#, VB, F#, C, C++, Phalanger,

PowerShell, Ruby, IronPython


.NET can build and run Windows applications, web
apps, web services, console applications, mobile
applications and more.
.NET has a huge number of powerful technologies
that can work with one another

and at the
center:

Now, .NET has reached version 4.5 and C#, as a language has

the most powerful features available today:


1. Closures;
2. Runtime generics;
3. Generics of primitive types
4. Delegates;
5. Events;
6. LINQ;
7. Extension methods;
8. First-class properties;
9. Operator overloading;
10. Indexers;
11. Anonymous types;
12. Expression trees;
13. Usingblocks;
14.No checked exceptions.
15. As of C# 4: thedynamictype,

Compiletime and
Runtime
When you compile a C# program, the output

of the compiler is not executable code.


Instead, it is a file that contains a special type
of pseudocode called Microsoft Intermediate
Language (MSIL).(CPU INDEPENDENT
->PORTABLE).
Microsoft Intermediate Language is turned
into executable code using a JIT compiler.
The JIT compiler converts MSIL into native
code on demand as each part of your program
is needed. This means that your program runs
nearly as fast as it would if it had been
compiled to native code in the first place.

IDE Visual Studio

THE C# LANGUAGE
Generally C++ syntax: types, variables,

statements, operators
OOP programming with new TYPES ( that
include both data and methods that work with
that data) and follow the OO principles.
Encapsulation
Inheritance
Polymorphism

ENCAPSULATION
Binding together code & the data it

manipulates into a black box like object. All


is kept inside and you can control what you let
others from the outside have access to.
Everything that defines and works with that
object is kept within.
This also supports abstractization. The app
becomes a set of objects that interact with
one another.
Why?

CLASSES AND OBJECTS


Basic unit of encapsulation is the CLASS
Classes define a types.
A class defines members (data,

methods, access). Collectively, the code


and data that constitute a class are called
its members.
OBJECTS are instances of a class.
You can create multiple instances/object

of the same class. Each instance has the same kind


of members. Each instance can hold a different state.

Classes
Fields
Methods
Constructors

ACCESS MODIFIERS

Default access modifier is private.

METHODS
[Access modifier] [return type] [name](parameter list)

{
}
OVERLOADING the ability to use multiple methods
with the same name but different parameter list.
void Add(int a)
void Add(int a , int b)
{ a = a+5;
{ a= a+b;
}
}
void Add(double a){}
Add(5); Add(5,6); .

Constructors
Block of code that is executed when a new

object is created.
Used to set default values.
Can have multiple constructors (overloading).
If there is no constructor defined, C# will
automatically add a default constructor.
Can not be inherited!

Syntax
...

public ClassName(parameter list)


{
//do stuff
}
Public access modifier (private by default)
ClassName the name of the class
No return type!
Call : ClassName object1 = new ClassName();

Reference Types
client1
Client client1 ;

Client client2 ;

client2 = client 1;

Client
Name=To
m
Client
Name=Bo
b

PROPERTIES
Syntax:

[access modifier] [return Type] [name]


{
get {}
set {}
}
Help you control what goes in and out of your
class (encapsulation)

Understanding static
There will be times when you will want to define a

class member that will be used independently of any


object of that class. Normally, a class member must
be accessed through an object of its class, but it is
possible to create a member that can be used by
itself, without reference to a specific instance.
To create such a member, precede its declaration with
the keyword static.
Variables declared as static are, essentially, global
variables. When objects of its class are declared, no
copy of a static variable is made. Instead, all
instances of the class share the same static variable.

INHERITANCE
The ability of an object to acquire all of the

members of another object while adding its


own.
When a class inherits another class it gains all
of its members and must add only things that
make it unique. (hierarchical classifications).
You can extend a class without having to
Class Employee
redefine.
string name;
Class Musician
int salary;
void
RaiseSalary()

string
music_type;

Class Violinist
void Play_Violin()

INHERITANCE BASICS IN
C#
Class DerivedClass : BaseClass

{}
BaseClass gain all of DerivedClass members (methods, properties,
fields. )
class TwoDShape
{
public double Width;
public double Height;
public void ShowDim() {
Console.WriteLine(Width + " and " + Height);
}
}

class Triangle : TwoDShape


{
public string Style; // style of triangle
public double Area() {
return Width * Height / 2;
}
}
Non private members
are not inherited.
Use protected !

2 other keywords
sealed - prevents inheritance. A sealed class

can not be derived.


abstract forces inheritance. An abstract
class must be inherited. An abstract class can
not be instantiated.
In C# you can not inherit from 2 different
classes! (unlike C++)

Constructor Inheritance
Constructors are not inherited by default.
Public DerivedClass(param list) : base (param

list)
{}
base keyword -> call a constructor from the
base class.
public Triangle(double x) : base(x) {
Style = "isosceles";
}

Virtual Methods and


Overriding
A virtual method is a method that is declared

using the virtual in a base class. The


defining characteristic is that it can be
redefined in one or more derived classes.
Thus, each derived class can have its own
version of a virtual method.
When a virtual method is redefined by a
derived class, the override modifier is used.

class TwoDShape
{
public virtual double Area() { return Width*Height;
}

}
class Triangle : TwoDShape
{
public override double Area() {
return Width * Height / 2;
}
}
class Circle:Two: TwoDShape
{
public override double Area() {
return (Math.Pi * Width *Width )/4;
}
}

POLYMORPHISM
Poly - WHAT?
Polymorphism (from Greek, meaning many forms)
Polymorphismin the context ofobject-oriented

programming, is the ability to create a variable, a


function, or an object that has more than one form.
The primary usage of polymorphism is the ability
ofobjectsbelonging to different types to respond
tomethod,field, orpropertycalls of the same
name, each one according to an appropriate typespecific behaviour.

We already used this?


Yes, we used method overriding.
Method overriding forms the basis for one of

C#s most powerful concepts: dynamic


method dispatch. Dynamic method dispatch is
the mechanism by which a call to an
overridden method is resolved at runtime,
rather than compile time. Dynamic method
dispatch is important because this is how C#
implements runtime polymorphism.

class Base {

public virtual void Who() {


Console.WriteLine("Who() in Base");
}
}
class Derived1 : Base {
public override void Who() {
Console.WriteLine("Who() in Derived1");
}
}
class Derived2: Base {
public override void Who() {
Console.WriteLine("Who() in Derived2");
}
}

Base baseOb = new Base();


Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who();
OUTPUT:
Who() in Base
Who() in Derived1
Who() in Derived2
JIT right?

At run time, objects of a derived class may be treated as

objects of a base class in places such as method


parameters and collections or arrays. When this occurs,
the object's declared type is no longer identical to its runtime type.
Base classes may define and implementvirtualmethods,
and derived classes canoverridethem, which means they
provide their own definition and implementation. At runtime, when client code calls the method, the CLR looks up
the run-time type of the object, and invokes that override
of the virtual method. Thus in your source code you can
call a method on a base class, and cause a derived class's
version of the method to be executed.

Overridden methods allow C# to support

runtime polymorphism. Polymorphism is


essential to object-oriented programming for
one reason: It allows a general class to specify
methods that will be common to all of its
derivatives, while allowing derived classes to
define the specific implementation of some or
all of those methods.

More advanced topics


Delegates
Events
Interfaces
Generic Types
Lambda Expressions
LINQ
Anonymous types
Expression trees
Dynamic features
Threading & Networking

Generics
A single class/method/field for ANY TYPE.

Stack<int> stack1 =new Stack<int>();


Stack<string> stack1 =new Stack<string>();
FAST (very)
SAFE
The new definition of REUSABLE CODE

Query and manipulate any data source from


C# code in the same way

WPF
WPF the next

generation User
Interface Technology
for WINDOWS

Thank you!

C# Fundamentals
Part II
C# Language Features:
Properties
Interfaces
Delegates & Events
Generics
Anonymous methods & Lambda Expressions
LINQ Integration

Events and Delegates


An event is a notification that some action has

occurred. Delegates and events are related


because an event is built upon a delegate.
Aneventin C# is a way for a class to provide
notifications to clients of that class when some
interesting thing happens to an object. The most
familiar use for events is in graphical user
interfaces; typically, the classes that represent
controls in the interface have events that are
notified when the user does something to the
control (for example, click a button).

Delegates
A delegate is an object that can refer to a

method. Therefore, when you create a


delegate, you are creating an object that can
hold a reference to a method. Furthermore,
the method can be called through this
reference. In other words, a delegate can
invoke the method to which it refers.
NOTE If you are familiar with C/C++, then it

will help to know that a delegate in C# is


similar to a function pointer in C/C++

Delegate Syntax
A delegate type is declared using the keyword

delegate. The general form of a delegate


declaration:
delegate [ret-type] name([parameter-list]);
Once created, a delegate instance can refer to
and call methods whose return type and
parameter list match those specified by the
delegate declaration. A delegate can be used
to call any method that agrees with its
signature and return type(static / instance).

A Quick Example
// Declare a delegate type.
delegate string StrMod(string str);
static string ReplaceSpaces(string s) {
Return s.Replace(' ', '-'); }
static string RemoveSpaces(string s) { . }
static string Reverse(string s) {.}
StrMod str1 = new StrMod(ReplaceSpaces);
string test = str1("This is a test.");
Console.WriteLine("Resulting string: " + test);
str1 = new StrMod(RemoveSpaces);
test= str1("This is a test."); .
OUTPUT
Resulting string: This-is-a-test.
Resulting string: Thisisatest.

Example Explained
Notice that StrMod takes one string parameter and

returns a string. Next, in DelegateTest, three static


methods are declared, each with a single parameter
of type string and a return type of string. Thus, they
match the StrMod delegate. These methods perform
some type of string modification.
StrMod strOp = new StrMod(ReplaceSpaces);
Notice how the method ReplaceSpaces( ) is passed
as a parameter. Only its name is used; When
instantiating a delegate, youspecify only the name of
the method to which you want the delegate to refer.
Invocation: str = str1("This is a test.");

Using Instance Methods


You can use instance methods just as easily:

StringOps so = new StringOps();


StrMod str1 = new
StringOps(so.ReplaceSpaces);
string test = strOp("This is a test.");

Multicasting
Multicasting

is the ability to create an


invocation list, or chain, of methods that will
be automatically called when a delegate is
invoked. Such a chain is very easy to create.
Simply instantiate a delegate, and then use
the += operator to add methods to the chain.
(or -= to remove).
One return (the last method in the list)

static void RemoveSpaces(ref string s) { . }


static void Reverse(ref string s) {}

StrMod strOp;
StrMod replaceSp = new
StrMod(ReplaceSpaces);
StrMod removeSp = new
StrMod(RemoveSpaces);
StrMod reverseStr = new StrMod(Reverse);
.
strOp = replaceSp;
strOp += reverseStr;
.
strOp(ref str); Output:tset-a-si-sihT

Covariance
There are two features that add flexibility to

delegates: covariance and contravariance.


Normally, the method that you pass to a
delegate must have the same return type and
signature
as
the
delegate.
However,
covariance and contravariance relax this rule
slightly, as it pertains to derived types.

Events
Another important C# feature is built upon

the foundation of delegates: the event. An


event is, essentially, an automatic notification
that some action has occurred. Events work
like this: An object that has an interest in an
event registers an event handler for that
event. When the event occurs, all registered
handlers are called. Event handlers are
represented by delegates.

Syntax
Events are members of a class and are

declared using the event keyword. Its most


commonly used form:
event event-delegate event-name;
Static methods and instance methods work
just as well

Basic Example
// Declare a delegate type for an event.
delegate void MyEventHandler();
class MyClass{
public event MyEventHandler SomeEvent;
// This is called to raise the event.
public void RaiseEvent() {
if(SomeEvent != null)
SomeEvent(); } }
class InterestedClass{ static void Handler() {Console.WriteLine("Event occurred in
InterestedClass1!!!!!!!");}
class InterestedClass2{ static void Handler() {Console.WriteLine("Event occurred in
InterestedClass2!!!!!!!");}
static void Main() {
MyClass evt = new MyClass();
// Add Handler() to the event list.
evt.SomeEvent += new MyEventHandler(InterestedClass1.Handler);
evt.SomeEvent += new MyEventHandler(InterestedClass2.Handler);
// Raise the event.
evt.OnSomeEvent(); }}
OUTPUT: Event occurred in InterestedClass1!!!!!!!
Event occurred in InterestedClass2!!!!!!!

The program begins by declaring a delegate type

for the event handler: delegate void


MyEventHandler(); All events are activated through
a delegate. Thus, the event delegate type defines
the return type and signature for the event.
Inside the class, an event called SomeEvent is
declared, using this line:
public event MyEventHandler SomeEvent;
An event handler called Handler( ) is created. In
this simple example, the event handler simply
displays a message, but other handlers could
perform more meaningful actions.
evt.SomeEvent += new
MyEventHandler(InterestedClass1.Handler);
Finally, the event is raised

.NET Event Guidelines


C# allows you to write any type of event you desire.

However, for component compatibility with the .NET


Framework, you will need to follow the guidelines Microsoft
has established for this purpose.
Thus, .NET-compatible event handlers will have this general
form:
void handler(object sender, EventArgs e)
{
// ...
}
Typically, the sender parameter is passed this by the calling
code. The EventArgs parameter contains additional
information and can be ignored if it is not needed.

Events and Delegates

Anonymous Methods
You will often find that the method referred to by a delegate is

used only for that purpose. In other words, the only reason for
the method is so it can be invoked via a delegate. The method
is never called on its own. In such a case, you can avoid the
need to create a separate method by using an anonymous
function.
An anonymous function is, essentially, an unnamed block of
code that is passed to a delegate constructor. One advantage
to using an anonymous function is simplicity. There is no need
to declare a separate method whose only purpose is to be
passed to a delegate.
Beginning with version 3.0, C# defines two types of
anonymous functions: anonymous methods and lambda
expressions.

Anonymous Methods
An anonymous method is one way to create an

unnamed block of code that is associated with a


specific delegate instance. An anonymous
method is created by following the keyword
delegate with a block of code.
// Declare a delegate type.
delegate void CountIt();
CountIt count1 = delegate { for(int i=0; i <= 5; i+
+)
Console.WriteLine(i);
}; // notice the semicolon
count1();

Passing Arguments
It is possible to pass one or more arguments to an

anonymous method. To do so, follow the delegate


keyword with a parenthesized parameter list. Then, pass
the argument(s) to the delegate instance when it is called.
Also, an anonymous method can return a value or use
outer variables normaly.
// Notice that CountIt now has a parameter.
delegate void CountIt(int end);
CountIt count2 = delegate (int end) {
for(int i=0; i <= end; i++)
Console.WriteLine(i);
};
count2(3);

Lambda Expressions
Although anonymous methods are still part of

C#, they have been largely superceded by a


better approach: the lambda expression.
Based on a distinctive syntactic element, the
lambda expression provides a powerful
alternative to the anonymous method.
Although a principal use of lambda
expressions is found when working with LINQ,
they are also applicable to (and commonly
used with) delegates and events.

The Lambda Operator


All lambda expressions use the lambda

operator, which is =>.


This operator divides a lambda expression
into two parts. On the left the input parameter
(or parameters) is specified. On the right is
the lambda body.
The => operator is sometimes verbalized as
goes to or becomes.
Common form: (param-list) => expr
x => x+ 2
n => n % 2 == 0
(low, high, val) => val >= low && val <=

Statement Lambdas
Multiline lambdas
// IntOp takes one int argument and returns an int
result.
delegate int IntOp(int end);
IntOp fact = n => {
int r = 1;
for(int i=1; i <= n; i++)
r = i * r;
return r;
};

Working with events


Lambda

expressions are especially useful


when working with events because often the
event handler is not called by any code other
than the event handling mechanism. As a
result, there is usually no reason to create a
standalone method. Thus, the use of lambda
expressions or anonymous methods can
significantly streamline event handling code.
evt.SomeEvent += (n) =>
Console.WriteLine("Event received. Value is " +
n);

Generics
Now we will examine one of C#s most sophisticated and

powerful features: generics.


The generics feature is so important because it enables the
creation of classes, structures, interfaces, methods, and
delegates that work in a type-safe manner with various kinds
of data. As you may know, many algorithms are logically the
same no matter what type of data they are being applied to.
For example, the mechanism that supports a queue is the
same whether the queue is storing items of type int, string,
object, or a user-defined class.
Prior to generics, you might have created several different
versions of the same algorithm to handle different types of
data. Through the use of generics, you can define a solution
once, independently of any specific type of data,

At its core, the term generics means parameterized types.

Parameterized types are important because they enable you to


create classes, structures, interfaces, methods, and delegates
in which the type of data upon which they operate is specified
as a parameter.
What about object?
C# has always given you the ability to create generalized code
by operating through references of type object. Because
object is the base class of all other classes, an object
reference can refer to any type of object. The problem was that
it could not do so with type safety because casts were needed
to convert
between the object type and the actual type of the data. This
was a potentially massive source of errors.
Generics fix this issue.
NOTE A Warning to C++ and Java Programmers: Although C#

generics are similar to templates in C++ and generics in Java,


they are not the same as either

Most Basic Example


// In the following Gen class, T is a type parameter
// that will be replaced by a real type when an object
// of type Gen is created.
class MyGenericClass<T> {
T ob; // declare a variable of type T
public Gen(T o) { ob = o; }
public T GetOb() {return ob;}
// Show type of T.
public void ShowType() {Console.WriteLine("Type of T is " +
typeof(T)); }}
.
MyGenericClass<int> iOb = new MyGenericClass<int>(102);
MyGenericClass<string> strOb = new
MyGenericClass<string>("Generics add power.");

Example Explained
Here, T is the name of a type parameter. This name is

used as a placeholder for the actual type that will be


specified when a object is created.
Notice that T is contained within < >
Any valid identifier could have been used, but T is
traditional.
Object creation:
MyGenericClass<int> iOb = new MyGenericClass<int>(102);
Type Safety
int v = iOb.GetOb(); // OK
iOb = strOb; // Wrong! will not compile, If we were to use object, it
would have compiled but at runtimean exception would be thrown

General Syntax
The generics syntax shown in the preceding

examples can be generalized. Here is the


syntax for declaring a generic class:
class class-name<type-param-list> { // ...
Here is the syntax for declaring a reference to a
generics class: class-name<type-arg-list> varname =
new class-name<type-arg-list>(cons-arg-list);

Other Features
Multiple generic parameters

class TwoGen<T, V> { }


TwoGen<int, string> tgObj =new TwoGen<int, string>(119, "Alpha
Beta Gamma");

Generic methods

public static bool CopyInsert<T>(T e, uint idx,


T[] src, T[] target) { }

Generic Constraints
When specifying a type parameter, you can

specify a constraint that the type parameter


must satisfy. This is accomplished through the
use of a where clause when specifying the
type parameter, as shown here:
class class-name<type-param> where typeparam : constraints { // ...

Constraint Types
C# defines the following types of constraints.
You can require that a certain base class be

present in a type argument by using a base


class constraint. This constraint is specified by
naming the desired base class.
Interface constraint
Constructor constraint
Type constraint

Base Class Constraint


A base class constraint serves two important purposes.

First, it lets you use the members of the base class


specified by the constraint within the generic class. For
example, you can call a method or use a property of the
base class. Without a base class constraint, the compiler
has no way to know what type of members a type
argument might have. By supplying a base class
constraint, you are letting the compiler know that all
type arguments will have the members defined by that
base class
The second purpose of a base class constraint is to
ensure that only type arguments that support the
specified base class are used.

Quick Example
class A { .
public void Hello() {
Console.WriteLine("Hello");
}}
// Class B inherits A.
class B : A { }
// Class C does not inherit A.
class C { }

class Test<T> where T : A {


T obj;
public Test(T o) { obj = o; }
public void SayHello() {
// OK to call Hello() because its declared by the base class A.

obj.Hello(); }}

A a = new A(); Test<A> t1 = new Test<A>(a);


B b = new B(); Test<B> t2 = new Test<B>(b);
C c = new C(); Test<C> t3 = new Test<C>(c); //
Error!

Collection Classes
The .NET Framework provides specialized

classes for data storage and retrieval. These


classes provide support for stacks, queues,
lists, and hash tables.
Collection classes are defined as part of

theSystem.Collectionsor
System.Collections.Genericnamespace.

Soyou want to store a couple of objects

togetherhow?
Array? a[50]= object1;
Right?....
Not really

The List type


Arrays do not resize dynamically. They are slow and if

you jump out of bounds you will get an exception


TheListtype 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.
It is generic
Examples: List<int>,

etc

List<string> , List<object>

Example:
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.
foreach (int prime in list)
{ Console.WriteLine(prime); }
This is how you access the elements of a list.

The Dictionary type


Fast lookups are critical. TheDictionarytype

in the C# language provides fast lookups with


keys to get values. It allows you to use keys
and values of any type, including ints and
strings. Dictionary requires a special syntax
form that may be unfamiliar.
Dictionary<object, object>
Example: Dictionary<int, string>

Example:
Dictionary<string, int> dictionary = new

Dictionary<string, int>();
dictionary.Add("cat", 2); dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
dictionary[cat] has the value 2 (where cat is the

key)
When Dictionary, is used in a foreach loop, it

returns an enumeration. In the case of Dictionary,


this enumeration is in the form of KeyValuePair

Here is how to access the elements of a


dictionary:
foreach(KeyValuePair pair in dictionary)
{
Console.Writeline(pair.Key);
Console.Writeline(pair.Value);
}
You can sort the dictionary either after keys or

values which makes them very flexible, useful


and easy to access.

LINQ via C#

Why LINQ?

The Motivation

Extensibility

Enter LINQ
LINQ is one of the most exciting features in C#.
LINQ stands for Language-Integrated Query. It encompasses a

set of features that lets you retrieve information from a data


source. It bridges the gap between the world of objects and the
world of data.
Traditionally, queries against data are expressed as simple
strings without type checking at compile time or IntelliSense
support. Furthermore, you have to learn a different query
language for each type of data source: SQL databases, XML
documents, various Web services, and so on.
LINQ gives to C# the ability to generate queries for any LINQcompatible data source.
Furthermore, the syntax used for the query is the sameno
matter what data source isused.

LINQ Fundamentals
At LINQs core is the query. A query specifies

what data will be obtained from a data source.


In order for a source of data to be used by
LINQ, it must implement the IEnumerable
interface.
To use the LINQ features, you must include
the System.Linq namespace.
The first and the fastest usage: working with
in memory collections of objects (classic C#
objects).

Basic Example
int[] nums = { 1, -2, 3, 0, -4, 5 };

// Create a query that obtains only positive


numbers.
var posNums = from n in nums
where n > 0
select n;
// Execute the query and display the results.
foreach(int i in posNums) Console.Write(i + " ");
135

Generalized Syntax
Generalizing, here is the syntax of the from

clause:
from range-variable in data-source
The next clause in the query is where. It
specifies a condition that an element in the
data source must meet in order to be obtained
by the query. Its general form is shown here:
where boolean-expression
Next, the selection:
select selection

Common Linq Operators


Similar to SQL

A query must begin with the keyword from

and end with either a select or group clause.


The select clause determines what type of
value is enumerated by the query.

Other Examples
Account[] accounts = { new Account("Tom",

"Smith", "132CK", 100.23), new


Account("Tom", "Smith", "132CD", 10000.00),
.. }
var accInfo = from acc in accounts
where acc.FirstName.StartsWith(To)
where acc.ID !=null
orderby acc.LastName, acc.FirstName,
acc.Balance
select acc;

Select New Objects and Nested


from Clauses
char[] chrs = { 'A', 'B', 'C' };
char[] chrs2 = { 'X', 'Y', 'Z' };
var pairs = from ch1 in chrs
from ch2 in chrs2
select new ChrPair(ch1, ch2);

Query Methods
The query syntax described by the preceding

sections is the way you will probably write


most queries in C#. It is convenient, powerful,
and compact. It is, however, not the only way
to write a query. The other way is to use the
query methods. These methods can be called
on any enumerable object, such as an array.

A LOT LESS CODE


var posNums = nums.Where(n => n >

0).Select(r => r);


var posNums = nums.Where(n => n >

0).OrderByDescending(j => j);

You can add as many mehods as you like

to form a chain.
It is possible to write Dynamic Querries
and Expression Trees

So what about Data


Sources?

MORE C#
The dynamic keyword

Multithreading
Networking

WPF a powerhouse for Modern UI


development with .NET & C#

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy