LINQ study notes

LINQ study notes

1. LINQ concept:

LINQ stands for language integrated Query. You can retrieval datafrom various sources (SQL database, list, object, xml, array) by just using LINQ,instead of different languages.

 

2. Basic grammar:

  <code>

Var queryResult =

  From nin names

  Wheren.StartWith(“S”)

  orderbyn descending

  Selectn;

</code>

var keyword: to declare a variable without figuring out the type of it.The compiler will infer the type for it based on the result type.

In this example, ‘names’ is the data source for this query. The datasource must implement theIEnumerableinterface.

Deferred Execution: The query result variable will only save the plan of retrievaluntil the result is visited.

Lambda operator ( => ):read as goes to or such that.

 

3. AdvancedOperation keywords:

  Order by:

  Orderbyn            or    names.OrderBy(n=>n)

  Orderbyn descending   or   names.OrderByDescending(n=>n)

  Orderbyobj.a1, obj.a2, obj.a3   or   objs.Orderby(…).ThenbyDescending(…).Thenby(…).select(…)

  Mathmethod:

queryResult.Count(),qR.Max(), qR.Min(), qR.Average(), qR.Sum(n=>(long)n)

  While retrieval from object and hope to only returnparticular member variables of object:

  ……..select object.id=1          or   objs.select(obj => obj.id = 1   

 ……. Selectnew {obj.a1, obj.a2, obj.a3 }    or   objs.select(obj => new { obj.a1, obj.a2, obj.a3}

  Distinct:

  Objs.select(obj=>……).distinct();

  Anyand All: to check whether the particular record or all records meet therequirement and return a Boolean result:

  bool

  boolanyUSA = objs.Any( obj => obj.country == “USA”)

bool allUSA = objs.All ( obj=>obj.country == “USA”);

  Groupby:

  Group objby obj.Region into cg

Grouping therecords by Region and save the group name as cg.

 TOP:

  Foreach( var item in objs.Take(5)){……}

Do operation ontop five records. Remember to order the records first, if it is necessary.

  Foreach(var item in objs.Skip(5)){…..}

Ignore the top five records while doing operation on the result group.

 First and FirstOrDefault:

qs.First( obj=>obj.Region == “Africa”);

qs.FirstOrDefault(obj=>obj.Region == “Africa”);

      These twostatement both return the first record in the records set. I believe theFirstOrDefault is better in most of cases, as you don’t need to worry about theerror processing if the result is null;


4. Invoke procedure using LINQ to SQL

    Just simplely use the precedure name as a function will make it. For example:

    List<obj> = dbContext.StoredProcedure1();


   



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值