Novedades Desafíos Papers y H-Zine Proyectos Foro
foros de discusión

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> An Introduction to LINQ
marioly
post Nov 1 2008, 09:02 AM
Post #1


Regia
Group Icon


Group: Root Admin
Posts: 2,007
Joined: 14-April 06
From: Mty, Nuevo Leon
Member No.: 38



What is LINQ? (Language Integrated Query)

Is a language integrated on the platform .NET to generate native data queries using a syntax similar to SQL. With LINQ one can generate a major abstraction, using a general tool which will function with several sources of information such as: xml, relational databases, even arrays or object lists (is able to operate over any object that implements IEnumerable)
LINQ has been added since the 3.0 version of .NET framework.

(DLinq and XLinq will be explain later)

Getting started with LINQ.


First example:

CODE
            int[] numeros = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            var resultados = from n in numeros
                             where (n%2 == 0)
                             select n;
            foreach (var i in resultados)
            {
                Console.WriteLine(i);
            }



It is a simple query to get familiarized with the language, anyone who has used SQL before will easily understand it. The query is applied over a whole-array selecting the elements that are even numbers, proving this with the residue generated by the module operator.

We can also apply them over other kinds of arrays:

CODE
string[] nombres = new string[] { "Daniel", "Marioly", "Marcela", "Omar" };
            var resultados = from n in nombres
                             where n.StartsWith("M")
                             select n;
            foreach (var i in resultados)
            {
                Console.WriteLine(i);
            }


This query requires the elements beginning with M. The example would show as output:

QUOTE
Marioly
Marcela


It is also possible to operate over the returned object, as follows:

CODE
select n.ToUpper()


This would return the same results, but this time the string would be upper-cased, since the ToUpper method was applied.


In the following example, an object list will be used with a "User" class, which only counts with two properties: "Nombre" (user name), and Genero (M = Male, F = Female).

CODE
    class User
    {
        public string Nombre
        {
            set;
            get;
        }

        public char Genero
        {
            set;
            get;
        }
    }
...
            List<User> usuarios = new List<User>
            {
                new User {Nombre = "Daniel", Genero = 'M'},
                new User {Nombre = "Marioly", Genero = 'F'},
                new User {Nombre = "Marcela", Genero = 'F'},
                new User {Nombre = "Omar", Genero = 'M'}
            };


Query:

CODE
    var resultados = from n in usuarios
                             where n.Genero == 'F'
                             select n;
            foreach (var i in resultados)
            {
                Console.WriteLine(i.Nombre);
            }


The comparison is generated just for it to return the users with "F" value in the gender field. This would give back 2 results.


It is also possible to reuse previous queries. If the following was added under the previous lines:

CODE
            usuarios.Add(new User { Nombre = "dna", Genero = 'F' });

            foreach (var i in resultados)
            {
                Console.WriteLine(i.Nombre);
            }


the new result would be:

QUOTE
Marioly
Marcela
dna


since the list which we are working with was altered.


Until this moment, only "select" and "from" have been seen, but LINQ has other operators such as "orderby". If we added the following to the query:
CODE
orderby n.Nombre ascending



the results would be ascendently ordered according to their name field.


LINQ can also advantage from lambda expressions for its methods. For example, the previous query could be replaced by:

CODE
            var res = usuarios.FindAll(n => n.Genero == 'F').OrderBy(a => a.Nombre);
            foreach (var i in res)
            {
                Console.WriteLine(i.Nombre);
            }



With this generalized typing and the possibility of working with several information sources, the programmer does not have to focus that much on data precedence and can dedicate himself to management of petition and result, something very practical and maintainable.

There is a lot to be explained, but I believe that it is enough for the moment. I have used LINQ for a while and it looks like a fabulous and very useful tool, and for many it could set the guideline to choose .net platform in possible developments.


Gracias.



--------------------
Go to the top of the page
 
+Quote Post
Mao
post Nov 1 2008, 09:45 AM
Post #2


Analu's Property
Group Icon


Group: Root Admin
Posts: 2,499
Joined: 29-March 06
From: Bucaramanga, Colombia.
Member No.: 24



no se de .net pero si quieres puede que aparesca en la revista solo muevelo a ya sabes donde y le dices a farid.

jejeje despues de escribir todo en ingles pones al final: Gracias..XD

/delete


--------------------
Chatear con Mao por MSN, Aqui. (NO RESPONDO PREGUNTAS PERSONALES!!!, ah y soy hombre..XD)



http://www.yashira.org/index.php?showuser=2488
Go to the top of the page
 
+Quote Post
crispunk
post Nov 1 2008, 10:02 AM
Post #3


Forista
****


Group: Hackerss Member
Posts: 422
Joined: 13-May 08
From: The deep abism
Member No.: 4,754



no se a mi me parecio muy interesante y facil de entender (como toooodo lo que hace marioly) pero no estoy muy seguro que tooodos los que entren aqui sepan ingles, no tendras una version en español, ps para que los demas entienda y se iluminen con tus conosimientos y explicaciones


--------------------
Visita mi Blog , Informatica, Musica, Skate.

Go to the top of the page
 
+Quote Post
nekro
post Nov 1 2008, 12:10 PM
Post #4


animich's baby
****


Group: Hackerss Member
Posts: 905
Joined: 18-March 06
From: /
Member No.: 2



jo me recordo a cosas pythoneras eso tongue.gif y luego diras que python es feo tongue.gif


--------------------
Contacto, dudas, sugerencias, quejas, etc a:
me@nekrox.com - msn@nekrox.com - http://nekrox.org

BLOG
Go to the top of the page
 
+Quote Post
xBrYaNx
post Nov 1 2008, 01:05 PM
Post #5


Forista
****


Group: Hackerss Member
Posts: 227
Joined: 20-March 06
From: Lima - Peru
Member No.: 5



Jejeje muy bueno justo estaba revisando sobre LINQ y muy interesante, pero no se si me puedas ayudar justo ahorita estaba viendo para usar en el metodo de sorting del GridView el LINQ, pero el criterio de ordenamiento que viene como string como lo utilizo solo he probado con concatenar y con Eval xDDD pero ninguno funciono, estare intentando, pero si sabes como, por favor lo compartes, muchas gracias y muy buen texto =)


--------------------
..:: Nelly ::.. ;)
Perfect Solution
[color="#0066cc"][/color]
Go to the top of the page
 
+Quote Post
marioly
post Nov 1 2008, 04:24 PM
Post #6


Regia
Group Icon


Group: Root Admin
Posts: 2,007
Joined: 14-April 06
From: Mty, Nuevo Leon
Member No.: 38



QUOTE(crispunk @ Nov 1 2008, 10:02 AM) *
no se a mi me parecio muy interesante y facil de entender (como toooodo lo que hace marioly) pero no estoy muy seguro que tooodos los que entren aqui sepan ingles, no tendras una version en español, ps para que los demas entienda y se iluminen con tus conosimientos y explicaciones

Supongo lo puedo traducir smile.gif . Se puede ver como una descortesía postear en ingles, pero no lo hago con esa intención. Quería empezar a postear artículos en ingles mas para practicarlo, ya que ahora no lo uso mucho en mi trabajo y a mi se me olvidan las cosas de volada! mellow.gif . Pero intentare poner las traducciones happy.gif


QUOTE(Mao @ Nov 1 2008, 09:45 AM) *
jejeje despues de escribir todo en ingles pones al final: Gracias..XD

Era para que todos entendieran


QUOTE(nekro @ Nov 1 2008, 01:05 PM) *
y luego diras que python es feo

si, phyton ES feo, no digo que no sea funcional, o util, pero feo es..


QUOTE(xBrYaNx @ Nov 1 2008, 01:05 PM) *
pero el criterio de ordenamiento que viene como string como lo utilizo solo he probado con concatenar y con Eval xDDD pero ninguno funciono

No te entiendo mucho, OrderBy("field DESC") ?







--------------------
Go to the top of the page
 
+Quote Post
xBrYaNx
post Nov 7 2008, 08:55 AM
Post #7


Forista
****


Group: Hackerss Member
Posts: 227
Joined: 20-March 06
From: Lima - Peru
Member No.: 5



Uhmm seguire revisando, en tu articulo usas .OrderBy(a => a.Field) pero no me acepta un string como parametro.


--------------------
..:: Nelly ::.. ;)
Perfect Solution
[color="#0066cc"][/color]
Go to the top of the page
 
+Quote Post
pelu
post Nov 7 2008, 09:20 AM
Post #8


Talibán del software libre.
Group Icon


Group: Colaborador
Posts: 633
Joined: 21-April 06
From: La concha de la lora
Member No.: 164



python es feo pero muy ordenado con su sintaxis , de hecho, lo bueno es que le obliga al desarrollador a hacer el codigo mas legible, lo siento, pero soy un obsesivo con las tabulaciones, llaves y demás ejjejeje

el articulo está bueno, aunque no tiene nada que ver, me hizo acordar a criteria de hibernate


--------------------
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

 

- Lo-Fi Version Time is now: 7th January 2009 - 11:15 AM