LINQ의 쿼리문법과 람다문법 비교

2012.09.06 14:07 개발언어/ASP.NET with MVC
LINQ의 쿼리문법과 람다문법 비교


 

Filtering

 

var col = from o in Orders

          where o.CustomerID == 84

          select o;

 

var col2 = Orders.Where(o => o.CustomerID == 84);

 

Return Anonymous Type

 

var col = from o in orders

          select new

          {

              OrderID = o.OrderID,

              Cost = o.Cost

          };

 

 

var col2 = orders.Select(o => new

      {

          OrderID = o.OrderID,

          Cost = o.Cost

      }

    );

 

Ordering

 

var col = from o in orders

          orderby o.Cost ascending

          select o;

 

 

var col2 = orders.OrderBy(o => o.Cost);

 

 

var col3 = from o in orders

           orderby o.Costdescending

           select o;

 

 

var col4 = orders.OrderByDescending(o => o.Cost);

 

var col9 = from o in orders

  orderby o.CustomerID, o.Costdescending

           select o;

 

 

var col6 = orders.OrderBy(o => o.CustomerID).

          ThenByDescending(o => o.Cost);

 

//returns same results as above

var col5 = from o in orders

           orderby o.Costdescending

           orderby o.CustomerID

           select o;

//NOTE the ordering of the orderby’s

 

 

Joining

 

var col = from c in customers

          join o in orders on

          c.CustomerID equalso.CustomerID

          select new

          {

              c.CustomerID,

              c.Name,

              o.OrderID,

              o.Cost

          };

 

var col2 = customers.Join(orders,

    c => c.CustomerID,o => o.CustomerID,

    (c, o) => new

        {

            c.CustomerID,

            c.Name,

            o.OrderID,

            o.Cost

        }

    );


Grouping

 

var OrderCounts = from o in orders

        group o by o.CustomerID intog

        select new

        {

            CustomerID = g.Key,

            TotalOrders = g.Count()

        };

 

var OrderCounts1 = orders.GroupBy(

         o => o.CustomerID).

         Select(g => new

         {

             CustomerID = g.Key,

             TotalOrders = g.Count()

         });

NOTE:
the grouping’s key is the same type as the grouping value. E.g. in above example grouping key is an int because o.CustomerID is an int.

Paging (using Skip & Take)

 

//select top 3

var col = (from o in orders

           where o.CustomerID == 84

           select o).Take(3);

 

 

 

var col2 = orders.Where(

           o => o.CustomerID == 84

           ).Take(3);

 

 

//skip first 2 and return the 2 after

 

var col3 = (from o in orders

           where o.CustomerID == 84

           orderby o.Cost

           select o).Skip(2).Take(2);

 

 

 

 

var col3 = (from o in orders

            where o.CustomerID == 84

            orderby o.Cost

            select o).Skip(2).Take(2);

 

Element Operators (Single, Last, First, ElementAt, Defaults)

 

//throws exception if no elements

var cust = (from c in customers

           where c.CustomerID == 84

           select c).Single();

 

 

 

var cust1 = customers.Single(

            c => c.CustomerID == 84);

 

//returns null if no elements

var cust = (from c in customers

            where c.CustomerID == 84

            selectc).SingleOrDefault();

 

 

 

var cust1 = customers.SingleOrDefault(

            c => c.CustomerID == 84);

 

//returns a new customer instance if no elements

var cust = (from c in customers

            where c.CustomerID == 85

            select c).DefaultIfEmpty(

              newCustomer()).Single();

 

 

 

 

var cust1 = customers.Where(

            c => c.CustomerID == 85

            ).DefaultIfEmpty(newCustomer()).Single();

 

//First, Last and ElementAt used in same way

var cust4 = (from o in orders

             where o.CustomerID == 84

             orderby o.Cost

             select o).Last();

 

 

 

 

var cust5 = orders.Where(

            o => o.CustomerID == 84).

            OrderBy(o => o.Cost).Last();

 

//returns 0 if no elements

var i = (from c in customers

         where c.CustomerID == 85

         selectc.CustomerID).SingleOrDefault();

 

 

 

var j = customers.Where(

        c => c.CustomerID == 85).

        Select(o => o.CustomerID).SingleOrDefault();

NOTE:

Single, Last, First, ElementAt all throw exceptions if source sequence is empty.

SingleOrDefault, LastOrDefault, FirstOrDefault, ElementAtOrDefault all
return default(T) if source sequence is empty.  i.e. NULL will be returned if T is a reference type or
nullable value type; default(T) will be returned if T is a non-nullable value type (int, bool etc).
This can be seen in the last example above.

 


 

Conversions

ToArray


string[] names = (from c in customers

                  select c.Name).ToArray();

ToDictionary


Dictionary<intCustomer> col = customers.ToDictionary(c => c.CustomerID);

Dictionary<stringdouble> customerOrdersWithMaxCost = (from oc in

 

(from o in orders                                    join c incustomers on o.CustomerID equals c.CustomerID

       select new { c.Name, o.Cost })

 

group oc by oc.Name into g

      select g).ToDictionary(g => g.Key, g => g.Max(oc => oc.Cost));

ToList


List<Order> ordersOver10 = (from o in orders

where o.Cost > 10

      orderby o.Cost).ToList();

ToLookup


ILookup
<intstring> customerLookup = 
           customers.ToLookup(c => c.CustomerID, c => c.Name);

 

 

신고
  1. Favicon of http://www.keydali.com BlogIcon 키큰난쟁이비밀방문자
    2012.09.06 19:44 신고 edit/del reply

    요새 요런 정보올린신다고 바쁘시네용~~ㅎㅎ

    • Favicon of http://ndolson.com BlogIcon 엔돌슨비밀방문자
      2012.09.08 13:11 신고 edit/del

      크크크 네 습작하는 게 있어서 공부하고 있어요^^
      프로그래밍 하는 데 괜찮은 정보 정리하고 있어요~
      조만간 윈도우 8 개발 도 해야 하고 할게 많네요

  2. Favicon of http://minimonk.net BlogIcon 구차니비밀방문자
    2012.09.15 08:10 신고 edit/del reply

    먼가 좋아 보이는데 검은건 글씨요.. 흰건 바탕이군요 ㅠ.ㅠ
    람다가 언어로서의 람다인가요? 문법으로서의 람다인가요?

  3. Favicon of http://blog.naver.com/vactorman BlogIcon 에로로비밀방문자
    2013.01.09 09:46 신고 edit/del reply

    좋은 정보 감사합니다. 제 블로그에 담아갈게요.
    혹시 원치 않으신다면 연락 주세요. 내리도록 하겠습니다.