现在的位置: 首页 > 综合 > 正文

LinQ To Object 基本用法

2012年03月17日 ⁄ 综合 ⁄ 共 10031字 ⁄ 字号 评论关闭

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;

AnyAll

确定数据是否满足某个条件,返回布尔类型

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)    //每个itemquantity 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)  //取相交项,list1list2 相同项,并且后面可以加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进行排序,默认是正序。默认为升序(AZ),可以添加descending关键字指定降序(ZA

//排序(正序)
            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)     listitem 使用 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 
表示 跳过count 个数据  处理分页可以使用 list.Skip((page-1)*pageSize).Take(pageSize);

 

SkipWhile

基于谓词函数跳过元素,知道某元素不在满足条件

Take

提取序列中指定位置之前的元素

list.Take(count) //count 表示 
选取count 个数据

TakeWhile

基于谓词函数提取元素,直到某元素不在满足条件

实例1(按照createdate 排序,并选取前 n类型的集合):

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

 

 

抱歉!评论已关闭.