inq的基本語法:var result = from item in container select item;
linq獲取數據子集: var result = from item in container where booleanexpression select item;
Select用法:
var selectedItems = from item in items
where item.ParentID == parentID
orderby item.SortIndex descending ,item.Name ascending
select item;
where : 根據條件查詢,如果 txtCustomerName中有值則匹配collection中的ClientName 是否包含這個txtCustomerName 的值
var list=collection.Where(t => (txtCustomerName.Text.Trim().Length == 0 || t.ClientName.ToUpper().IndexOf(txtCustomerName.Text.Trim().ToUpper()) >= 0));
Filtering【過濾】
篩選指將結果集限制為只包含那些滿足指定條件的元素的操作,下面的示例使用Where子句來從數組中篩選那些具有特定長度的字符串。
string[] words = { "the", "quick", "brown", "fox", "jumps" };
IEnumerable<string> query = from word in words
where word.Length == 3
select word;
Any和All
確定數據是否滿足某個條件,返回布爾類型
bool anyUSA=customers.Any(c=>c.Country=="USA") //如果對於列表中的任意顧客,λ表達式是true,就返回true bool allAsia=customers.All(c=>c.Region=="Asia") //列表中的所有顧客來自亞洲,返回true。
LInq 遞歸實現
private BuildExpression(IEnumberable<string>enumberableList){...} //定義 function return factory =>{ BuildExpression(factory); //遞歸實現的function };
list.Select(t=>t.CreateDate).SeperateToString(","); //select createdate 字段集合並組成string 返回
list.Select(t=>new DataEntity{Name=t.Name,Value=t.Value}); //selectTypeOf(list) 類型中的某些字段到新的 DataEntity 實例中
list.Sort( (x, y) => StringComparer.CurrentCultureIgnoreCase.Compare(x.CreateDate,y.CreateDate)); //x,y 表示 T的一個實例, x 在y前面表示 順序排列,如果變為Compare(y.CreateDate,x.CreateDate)表示倒序排列
list.Select(item=>item.Quantity).Min() //或取list中 數量最少的記錄
list.Min(item=>item.Quantity) //或者list中 數量最少的記錄
list.Orderby(t=>t.Quantity).thenBy(t=>t.Price).FirstOrDefault(); //變相實現list min 對 兩個屬性進行比較
list.InsertRange(0,list2) //在list的指定位置插入list 2
list.ForEach(item=>item.Quantity+=1) //每個item的quantity 加1
list.Concat (list2) // 兩個同類型的list ,list2組合起來,並且不去除相同記錄,順序為 list2 追加到list 后面
list.Union(list2,, new LambdaComparer<string>((a, b) => a == b))
list.Union(list2) //兩個同類型的list ,list2 組合, 去除相同記錄,並追加到list 后面
list.Except(list2) //從list中選擇 除了 list2中含有的其他所有數據
list.Intersect (list2) //取相交項,取list1,list2 相同項,並且后面可以加compare 條件
組合應用
以下應用實現了 多個node 和 connector 之間的關聯. node 可能沒有與connector 相連接, 但是connector 必須與node 連接。實現 取出所有connector , 並取出有連接線的node 和 沒有連接線的node
var listFlowActions = new List<FlowAction>();
var connectors = flowActions.Where(i => i.ActionType == MongoConstants.FlowActions.Connector && IsFlowActionExists(i.SourceFlowActionId)
&& IsFlowActionExists(i.TargetFlowActionId)).OrderBy(connection => connection.Index);
var allNodes = flowActions.Where(i => i.ActionType != MongoConstants.FlowActions.Connector); var connectedNodes = new List<FlowAction>();
connectors.Each(t => connectedNodes.Add(allNodes.Where(i => i.Id == t.SourceFlowActionId).FirstOrDefault()))
.Each(t=>connectedNodes.Add(allNodes.Where(i=>i.Id==t.TargetFlowActionId).FirstOrDefault())); var notConnectedNodes = connectedNodes.Except(connectedNodes) .Each((i, index) => i.X = index * 100).Each(i => i.Y = 50);;
Linq 查詢方法
public static bool SaveEmployeeToFunctionPoint(Guid functionPointID, List<Guid> employeeIDList){ var oldCollection = new EmployeeToFunctionPointCollection(); oldCollection.GetMulti(EmployeeToFunctionPointFields.FunctionPointId == functionPointID); var oldIDList = from item in oldCollection select item.EmployeeId; var newList = from item in employeeIDList where !oldIDList.Contains(item) selectitem; //選擇 employeeidlist中不與oldidlist中重復的項 var trans = new Transaction(System.Data.IsolationLevel.ReadCommitted, "SaveEmployeeToFunctionPoint"); try{ foreach (Guid empID in newList){ var entity = new EmployeeToFunctionPointEntity{ EmployeeId = empID, FunctionPointId = functionPointID, IsMain = false }; trans.Add(entity); entity.Save(); } trans.Commit(); return true; } catch (Exception e){ trans.Rollback(); return false; } }
inq查詢中的常用函數
count<T>() 獲取linq查詢表達式返回的項數。對集合中的元素進行計數,還可以僅滿足某一謂詞函數的元素進行計數
list.Count(item=>item.Name=='test') //查詢list中 name 為 test的記錄條數
static void FunLinq() { int[] numbers = { 2, 10, 30, 15, 1, 22 }; //輸出大於10的總數 int count = (from i in numbers where i > 10 orderby i select i).Count<int>(); Console.WriteLine(count);//輸出:3 }
Reverse<T>對linq結果集中的項進行反轉
var newnumbers = from i in numbers select i; foreach (var p in numbers.Reverse()) { Console.WriteLine(p);//輸出22 1 15 30 10 2 }
orderby 對linq進行排序,默認是正序。默認為升序(A到Z),可以添加descending關鍵字指定降序(Z到A)
//排序(正序) string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2" }; var newn = from i in games orderby i ascending select i; foreach (var p in games) { Console.Write(p+",");// }
用語法排序
list.OrderBy(entity=>entity.CreateDate); //entity 表示 T的一個實例,按照 createdate 順序排列,反之 則使用 listOrderByDescing逆序排序
varquerResults=names.OrderByDescending(n=>n)
多級排序
var queryResult= from c in customers Orderby c.Region,c.Country,c.City Select new(c.ID,c.Region,c.County,C.City)
方法語法
var queryResult=customers.OrderBy(c=>c.Region).ThenByDescending(c=>c.County).ThenBy(c=>c.City).select(c=>new{c.ID,c.Region,c.Country,c.City})
Distinct()移除數據中的重復項目
//排序(正序) string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2", "Shock2"}; var newn = from i in games orderby i ascending select i; foreach (var p in games.Disinct()) { Console.Write(p+",");// }
聚合操作
//聚合操作 //最大值 var maxi =( from i in games orderby i ascending select i).Max(); //最小值 var mini = (from i in games orderby i ascending select i).Min(); //平均值 var avar = (from i in numbers orderby i ascending select i).Average(); //總和 var sum = (from i in numbers orderby i ascending select i).Sum(); list.Sum(item=>item.Quantity); //合計,合計list中的quantity 字段 querResults.Sum(n=>(long)n) //無參數返回32位int類型,n=>(long)n轉化為64位,防止溢出
Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>)方法可簡化在值序列上執行的計算。此方法的工作原理是對 source 中的每個元素調用一次 func。每次調用 func 時,Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) 都將傳遞序列中的元素和聚合值(作為 func 的第一個參數)。將 source 的第一個元素用作聚合的初始值。用 func 的結果替換以前的聚合值。Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>)返回 func 的最終結果。
下面的代碼示例演示如何使用 Aggregate 從一個字符串數組生成一個句子。
string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words.string[] words = sentence.Split(' '); // Prepend each word to the beginning of the // new sentence to reverse the word order.string reversed = words.Aggregate((workingSentence, next) => next + " " + workingSentence); outputBlock.Text += reversed + "\n"; // This code produces the following output://// dog lazy the over jumps fox brown quick the
list.Aggregate((x,y)=>xyexpression)
//聚合函數,將 list中數據 分別進行 聚合
比如 : var list = new
List<string>(){"1","12","13","14","15","19","111","121","","23"};
var strReturn = list.Aggregate("return ", (x, y) => (string.IsNullOrEmpty(y) ? x : x + y + " && "));
strReturn = strReturn.Substring(0, strReturn.Length - 3) + ";";
結果為: return 1 && 12 && 13 && 14 && 15 && 19 && 111 && 121 && 23 ;
例子的功能也可以簡化為 list.Join("&&")
list.Join(stringSeperator) 將list中item 使用 stringSeperator 連接起來,如上面的例子
Projection Operations【投影】(在查詢中創建新對象)
Select中不允許有多個字段
投影是指將對象轉換為一種新形式的操作,該操作通常值包含那些隨后將要使用的屬性。通過使用投影,可以構建依據每個對象生成的新類型。你可以映射屬性,並對該屬性執行數學函數。還可以在不更改原始對象的情況下映射該對象,下面的示例中的Select子句來映射字符串列表中的每個字符串的第一個字母。
List<string> words = new List<string>() { "an", "apple", "a", "day" }; var query = from word in words select word.Substring(0, 1);
SelectMany,下面的示例中使用多個from子句或from子句來映射字符串列表中每個字符串中的每個單詞。
List<string> phrases = new List<string>() { "an apple a day", "the quick brown fox" }; var query = from phrase in phrases from word in phrase.Split(' ') select word; var queryResult= from c in customers Where c.Region=="North America" Select new(c.City,c.Count,c.Sales) var queryResult=customers.where(c=>c.Region=="North America").select(c=>new(c.City,c.Count,c.Sales))
Partitioning【數據分區】
LINQ中的分區指的是在不重新排列元素的情況下,將輸入序列划分為兩部分,然后返回其中的一部分的操作。
Skip |
跳過序列中指定位置之前的元素 list.Skip(count) //count
|
SkipWhile |
基於謂詞函數跳過元素,知道某元素不在滿足條件 |
Take |
提取序列中指定位置之前的元素 list.Take(count) //count 表示 |
TakeWhile |
基於謂詞函數提取元素,直到某元素不在滿足條件 |
實例1(按照createdate 排序,並選取前 n個T 類型的集合):
list.OrderBy(entity==>entity.CreateDate).Take(n).ToList<T>();
下面的代碼示例中使用Skip子句來跳過字符串數組中的前四個字符串,然后返回此數組中剩余的字符串
string[] words = { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" };
var query = words.Skip(4);
下面的代碼示例中使用SkipWhile子句來跳過數組中字符串的首字母為”a”的字符串。返回此數組中的剩余字符串
string[] words = { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" };
var query = words.SkipWhile(u => u.Substring(0, 1) == "a");
下面示例使用Take子句來返回字符串數組中的前兩個字符串
string[] words = { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" };
var query = words.Take(2);
下面示例中使用TakeWhile子句來返回數組中的字符串長度小於或等於5的字符串
string[] words = { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" }; var query = words.TakeWhile(u => u.Length < 6);
下面是分頁帶排序的方法。
dbconn 是Modle的對象,BidRecord 是一個實體,P=>p.bid_id 是排序的條件
OrderBy 是排序(后面是條件)然后要查詢所有的,在所有的數據中在查詢你要分頁的數據,skip是在分頁在前有多少條數據,也就是在當前頁數據之前的數據總和,(跳過序列中指定數量的元素,然后返回剩余的元素。)pageSize*(pageIndex-1),Take是返回多少條數據,也就是pageSize!
dbconn.BidRecord.OrderBy(p=>p.bid_id).ToList<BidRecord>().OrderBy(p => p.bid_id).Skip(skip).Take(take).ToList<BidRecord>();
Grouping【數據分區】
ToLookup |
根據鍵選擇器函數將元素插入到Lookup<Tkey,TElement>中 |
|
組合查詢
var queryResult= from c in customer Group c by c.Region in to cg Select new(TotalSales=cg.Sum(c=>c.Sales),Region=cg.Key)
組合查詢中的數據通過一個鍵(key)字段來組合,么個組中的所有成員都共享這個字段值。這個例子中,鍵字段是Region:
Group c by c.Region
要計算每個組的總和,應生成一個新的結果集cg:
Group c by c.Region into cg
在select子句中,投射了一個新的匿名類型,其屬性是總銷售量(通過引用cg結果集來計算)和組的鍵字段值,后者是用特殊的組key來引用的:
Select new(TotalSales=cg.Sum(c=>c.Sales),Region=cg.Key)
Lookup<TKey,TElement>表示映射到一個或多個值得各個鍵的集合
Lookup<TKey,TElement>類似於Dictionary<TKey,TValue>。不同之處在於:Dictionary<TKey,TValue>將各個鍵映射到單個值,而Lookup<TKey,TElement>將各個鍵映射到值得集合。
Element【元素操作】
元素操作從一個序列返回單個特定元素
ElementAt |
返回集合中指定索引處得元素 |
ElementAtOrDefault |
返回集合中指定索引處得元素;如果超出范圍,則返回默認值 |
First |
返回集合中的第一個元素或滿足條件的第一個元素 |
FirstOrDefault |
返回集合中的第一個元素或滿足條件的第一個元素。如果沒有這樣的元素,則返回默認值 |
Last |
返回集合中的最后一個元素或滿足條件的最后一個元素 |
LastOrDefault |
返回集合中的最后一個元素或滿足條件的最后一個元素。如果沒有這樣的元素,則返回默認值 |
Single |
返回集合中的唯一元素或滿足條件的唯一元素 |
SingleOrDefault |
返回集合中的唯一元素或滿足條件的唯一元素。如果沒有這樣的元素或集合不是正好包含一個元素,則返回默認值 |
Aggregate |
對集合值執行自定義聚合運算 |
Longcount |
對大型集合中的元素進行計數,還可以僅滿足某一謂詞的元素進行計數 |
Converting Data Types
方法名 |
說明 |
AsEnumerable |
返回類型為IEnumerable<T>的輸入 |
AsQueryable |
將IEnumerable轉換為(泛型)IQueryable |
Cast |
將集合的元素強制轉換為指定的類型 |
OfType |
根據值強制轉換為指定類型的能力篩選值 |
ToArray |
|
ToDictionary |
|
ToList |
|
ToLookUp |
|