EF 拉姆达 linq if else (整理)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                EF 拉姆达  linq  if else (整理)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                ?
首先想到:結果不正確!
var data0 = db.T_Plants2; //這里加.AsQueryable()if (locationType == 1){.Where(d => d.NaturalEcosystem == true);}else{.Where(d => d.BuiltUpArea == true);}.Select(d => new{AnimalID = d.PlantID,Species = d.Species,}).ToList();一、納姆達方式
var data0 = db.T_Plants2.AsQueryable(); //這里加.AsQueryable()if (locationType == 1){data0= data0.Where(d => d.NaturalEcosystem == true);}else{data0 = data0.Where(d => d.BuiltUpArea == true);}var data2= data0.Select(d => new{AnimalID = d.PlantID,Species = d.Species,}).ToList();// 這里Iqueryable 無法轉化為list必須用新對象data2接收;?
三元表達式:
//var data2 = db.T_Plants2// .Where(d=> locationType == 1 ? d.NaturalEcosystem == true : d.BuiltUpArea == true)
// .Select(d => new//{// AnimalID = d.PlantID,// Species = d.Species,// Genus = d.Genus,// Family = d.Family//}).ToList();
?
二、Linq方式
//案例一
from p in db.productsselect new{Owner = (p.price > 0 ?from q in db.Users select q.Name :from r in db.ExternalUsers select r.Name)}?//案例二
from p in db.products if p.price>0 select new {Owner=from q in db.Usersselect q.Name } else select new {Owner = from r in db.ExternalUsersselect r.Name }?//案例三
private string getValue(float price) {if(price >0)return "debit";return "credit"; }select new {p.PriceID, Type = getValue(p.Price)};?三、拓展
多條件查詢,自己構造 filter條件
View Code例如:
?
//對某一字段的查詢,查詢關鍵字是兩個或兩個以上的字符串,但查出來的相鄰兩個關鍵字的間距必須在20個字符以內 void Main() {var keys = new List<string>();keys.Add("女子");keys.Add("須發"); // keys.Add("如男子");var filters = new List<System.Linq.Expressions.Expression<Func<LINQPad.User.CM_BookPageDetail, bool>>>();foreach(var key in keys)filters.Add(item=>item.Content.Contains(key));for(var i=0;i<keys.Count ;i++){if(i>0){var lastKey = keys[i-1];var currentKey = keys[i];filters.Add(item=> item.Content.IndexOf(currentKey) - item.Content.IndexOf(lastKey) < 20);}}var query = from item in CM_BookPageDetailsselect item;foreach(var filter in filters)query = query.Where(filter);query.Take(10).Dump(); }?多條件查詢通用方法,重構 where、orderby 方法
https://www.cnblogs.com/hao-1234-1234/p/11271840.html
?
參考文章
http://www.it1352.com/401595.html
https://stackoverflow.com/questions/443044/if-else-in-linq
https://q.cnblogs.com/q/73479/
?
轉載于:https://www.cnblogs.com/hao-1234-1234/p/11271672.html
總結
以上是生活随笔為你收集整理的EF 拉姆达 linq if else (整理)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: CentOS6.4 Install FT
 - 下一篇: Springboot + Mybati