C#10进阶语法(三)

182 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

前言

今天我们来讲一讲C#的linq语法,以及特性,这都是我们学习.netcore的基础,我们一起来看一看吧!

linq(where)

linq to object : 数组、list集合等 --内存里的数据

linq to sql : 查询数据库 --数据库中的数据

linq to XML : 查询XML文件

1.自定义linq

public  class linqshow{
    public void show{
    List<Students> list3 = StudenList.AntWhere(x => x.Age<20).ToList();
    }
}
​
​
​
​
public static class LinqExtend {
    
    public static IEnumerable<TSource> AntWhere<TSource>(this IEnumerable<TSource> resource, Func<TSource,bool> func){    
   List<TSource> list2 = new List<TSource>();
    foreach(var item in resource){
        if(func.Invoke(item)){
            list2.Add(item)
        }
    }
        
    }
}

2.官方的Linq(扩展方法方式)

//var list4 = StudenList.Where(x=>x.Age<20);
​
List<Students>  list4 = StudenList.Where(x=>x.Age<20).ToList();

3.表达式方式的

List<Students>  list5 = (from s in StudentList
                        where s.Age<20
                        select s).ToList();

Linq(Select)

select就是映射到另一个对象

public void show(){
//扩展方法用法
  var query = StudentList.Select(s => new StudentModel{
     Id=s.Id, 
     Name=s.Name
  }) 
  
  //表达式用法
  //var query2 = from s in StudentList
   //           select new StudentModel{
   //            Id=s.Id, 
   //  Name=s.Name
    //           }
}

Linq(Join)

多表连接查询

  public List<JobviewModel> GetJobs()
        {
            //var jobs = from j in _context.Jobs
            //           join cp in _context.Companys on j.CompanyId equals cp.Id
            //           join ct in _context.Cities on j.WorkPlace equals ct.Id
            //           select new JobviewModel
            //           {
            //               Id = j.Id,
            //               JobName = j.JobName,
            //               JobPay = j.JobPay,
            //               Welfare = j.Welfare,
            //               WorkExperince = j.WorkExperince,
            //               WorkPlace = j.WorkPlace,
            //               WorkArea = j.WorkArea,
            //               PublishTime = j.PublishTime,
            //               PositionInfo = j.PositionInfo,
            //               Company = j.Company,
            //               City = j.City
            //           };
            //return jobs.ToList();
           var jobs= _context.Jobs.Join(_context.Companys, j => j.CompanyId, c => c.Id, (j, c) => new JobviewModel
            {
                Id = j.Id,
                JobName = j.JobName,
                JobPay = j.JobPay,
                Welfare = j.Welfare,
                WorkExperince = j.WorkExperince,
                WorkPlace = j.WorkPlace,
                WorkArea = j.WorkArea,
                PublishTime = j.PublishTime,
                PositionInfo = j.PositionInfo,
                Company = c,
                City = j.City
​
            }).Join(_context.Cities, jv => jv.WorkPlace, c => c.Id, (jv, c) => new JobviewModel
            {
                Id = jv.Id,
                JobName = jv.JobName,
                JobPay = jv.JobPay,
                Welfare = jv.Welfare,
                WorkExperince = jv.WorkExperince,
                WorkPlace = jv.WorkPlace,
                WorkArea = jv.WorkArea,
                PublishTime = jv.PublishTime,
                PositionInfo = jv.PositionInfo,
                Company = jv.Company,
                City = c
​
​
            }).ToList();
​
            return jobs;
​
        }

Linq的其他方法

var query = StudentList
     //  .Skip(6)    跳过
      //  .Take(6)   取
        //  .OederBy(s=>s.Name)  排序
         //  .OederByDescending(s=>s.Id) 倒序
            .where(s => s.Name.Contains("A")) 模糊查询

IQueryable类型

实现了IEumerable接口

数据库的数据用这种类型接收

特性

应用场景:框架上、类上面、方法上面、属性上面、字段上面、参数上面。。。

特性的本质:类,继承自(Attribute类)

特性简单的定义、查找、使用

(定义--》使用--》通过反射查找特性--》调用)

//pragram.cs
    
    Student student = new Student();
    
     string tableName = CustomAttribute.GetTableNameAttribute(student)
     
         
         
         
//TableAttribute.cs
            
​
  //特性配置      [AttributeUsage(AttributeTarget.Class,AllowMutiple=true,Inherited = true)]
     
   //特性定义
   public class TableAttribute : Attribute{
       
       public string TableName{get;set;}
       public TableAttribue(){
           
       }
       
       public TableAttribue(string tableName){
           TableNametableName
       }
       
   } 
       
   
​
//CustomeAttribute.cs
(这里通过反射得到表名)
 public CustomeAttribute{
     
     public static string GetCustomAttribute<T>(T mode) where T:class{
         
         Type type = typeof(T);
         if(type.IsDefined(typeof(TableAttribute),true)){
          var attribute = type.GetCustomeAttributes(typeof(TableAttribute),true)   
    return ((TableAttribute)attribute[0]).TableName;
             
         }
         else{
             return type.Name
         }
     } 
     
 }

常用的特性编写

//student.cs
public class Student{
    
    [key] //这个属性是主键
    public int Id{get;set;}
    
             [StringLength(maxinumLength:50,MiniumLength:6)] //字符串长度
    public string Name{get;set;}
    
      [EmailAdress] //识别邮箱地址
    public string Email{get;set;}
    
      [Required] //属性不能为空
    public int Age{get;set;}
    
      [Display(Name="电话号码")] //显示字段别名
    public int PhoneNumber{get;set;}
    
}

定义一个抽象类 ,其他定义的特性类继承它(方便代码的重用):

//CommonValidateAttribute.cs
​
  abstract class CommonValidateAttribute:Attribute
  {
      public abstract bool IsValidate(object dataValue);
  }

后面就各种特性类继承(实现抽象类):

//KeyAttribute.cs
​
   public class KeyAttribute:CommonValidateAttribute{
       punblic bool IsPrimaryKey{get;set} = true;
       
   public override bool IsValidate(object dataValue){
       return IsPrimaryKey;
   }
   }
​
​
​
​
​
//RequiredAttribute.cspublic class RequiredAttribute:CommonValidateAttribute{
      
       
   public override bool IsValidate(object dataValue){
       return dataValue!=null&&dataValue.ToString().length!=0 ;
   }
   }

....

反射查找:

//CustomAttribute.cspublic static bool Validate<T>(T model)
{
    //获取所有的属性和特性】
    PropertyInfo propertyInfos = model.GetType().GetPropeties();
    //遍历属性和读取特性
    foreach(var property in propertyInfos)
    {
        if(property.IsDefined(typeof(CommonValidateAttribute),true))
        {
            var attributes = property.GetCustomAttribute(typeof(CommonValidateAttribute),true)
                
              foreach(item in attributes)
              {
                  CommonValidateAttribute attribute= item as CommonValidateAttribute;
                  if(!attribute.IsValidate(property.GetValue(model)))
                  {
                      return false 
                  }
              }
        }
    }
    return true
}

调用:

//pragram.cs
​
  Student stu = new Student(){
      Id=1,
      Name="aaa",
      Age=18,
      Email="123456789@qq.com",
      PhoneNumber="123456789"
  };
​
var result = CustomAttribute.IsValidate(stu);
总结:今天的内容就到这里了,我们一步步来,加油!