Linq笔记

2018/04/27 DotNetCore 共 6985 字,约 20 分钟

工作内容的临时备忘,Linq代码片段。

LinqPad调试

linqpad旗舰版结合abp vnext.直接嵌入visualStudio2022的Efcore中调试注入的实体仓储。

L727hwjPLq

Linq中Aggregate累加计算

image-20220408144439310

 
                            //foreach (var dic in itemData)
                            //{
                            //    enumList = enumList + dic.Data_Name + ";";
                            //} 
                            
                            var enumList = itemData.Aggregate("", (current, dic) => current + dic.Data_Name + ";");//累加拼接字符串

Linq中LeftJoin处理_左连接Linq等价处理

image-20220322140256469

左链接:join之后into 到一个临时表,然后from XXX in 这个临时表

参考:https://docs.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins

image-20220317230444564

image-20220318233922460

LinqPad的坑

LinqPad里面写Linq的时候,代码和visualStudio中还是有非常大的区别的,Linqpad对于数据类型转换更加敏感。

image-20220221170712631

image-20220221171036730

分组筛选统计

var oneRowCount = (
                    from item in bgeManualMonitorPointDetailEntities
                    group item by
                        new { item.ObjectName }
                    into g
                    select new
                    {
                        Name = g.Key.ObjectName,
                        DropDown = g.Count(x => !string.IsNullOrEmpty(x.DropDown) && x.DropDown != Activated),
                        Temperature = g.Count(x => !string.IsNullOrEmpty(x.Temperature) && x.Temperature != Activated),
                        CrackWidth = g.Count(x => !string.IsNullOrEmpty(x.CrackWidth) && x.CrackWidth != Activated),
                        Distance = g.Count(x => !string.IsNullOrEmpty(x.Distance) && x.Distance != Activated),
                        Reactivity = g.Count(x => !string.IsNullOrEmpty(x.Reactivity) && x.Reactivity != Activated),
                        AngleX = g.Count(x => !string.IsNullOrEmpty(x.AngleX) && x.AngleX != Activated),
                        AngleY = g.Count(x => !string.IsNullOrEmpty(x.AngleY) && x.AngleY != Activated),
                        CableForce = g.Count(x => !string.IsNullOrEmpty(x.CableForce) && x.CableForce != Activated),
                        WindSpeed = g.Count(x => !string.IsNullOrEmpty(x.WindSpeed) && x.WindSpeed != Activated),
                        WindDirection = g.Count(x =>
                            !string.IsNullOrEmpty(x.WindDirection) && x.WindDirection != Activated),
                        Wet = g.Count(x => !string.IsNullOrEmpty(x.Wet) && x.Wet != Activated),
                        Height = g.Count(x => !string.IsNullOrEmpty(x.Height) && x.Height != Activated),
                        Overturn = g.Count(x => !string.IsNullOrEmpty(x.Overturn) && x.Overturn != Activated),
                    }).ToList();
                var outPutListData = new List<ObjectNodeOutPutListDto>();

Linq分页:

skip 之后再take, 不能反正来,反着来取不到值。

image-20220518150812658


        public async Task<ReturnPageWithDataDto> GetThirdUnitList(ThirdUnitInputDto inputDto)
        {
            var dataList = await (from p in _instituTionsRepository
                                  join q in _sysAreaRepository
                                  on p.Area_Code equals q.AreaCode
                                  where p.Info_Valid == 0&&p.Inst_Att==6
                                  select new ThirdUnitOutputDto
                                  {
                                      Id = p.Id,
                                      UnitName = p.Inst_Name,
                                      AreaCode = p.Area_Code,
                                      AreaName = q.AreaName,
                                      UnitPhone = p.unit_phone,
                                      ContactName = p.Contact_Name,
                                      ContactNumber = p.Contact_Number,
                                      CreateTime = p.create_time
                                  }).ToListAsync();
            int skip = (inputDto.PageIndex - 1) * inputDto.PageSize;
            dataList = dataList.Skip(skip).Take(inputDto.PageSize).OrderByDescending(o => o.Id).ToList();
            if (!string.IsNullOrEmpty(inputDto.UnitName))
            {
                dataList = dataList.Where(p => p.UnitName.Contains(inputDto.UnitName.Trim())).ToList();
            }
            if (!string.IsNullOrEmpty(inputDto.ContactName))
            {
                dataList = dataList.Where(p => p.ContactName.Contains(inputDto.ContactName.Trim())).ToList();
            }
            return ReturnPageWithDataDto.ToResultSuccess(
                         msg: "获取数据成功",
                         PageIndex: inputDto.PageIndex,
                         PageSize: inputDto.PageSize,
                         TotalRow: dataList == null ? 0 : dataList.Count,
                         modelData: dataList
                         );
        }

代码中Linq调试

如果是要重构或者是查找bug,使用linqpad贴入代码,然后稍微把一些错误给修复之后,就可以看到执行结果。

image-20211208192709315

var loadSource = (from lod in detection_load_tests
                                  join info in bge_infos on lod.Bge_id equals (int)info.Id into lodInfoData
                                  from infod in lodInfoData.DefaultIfEmpty()
                                  join usr in sys_user_details on lod.Upload_user_id equals (int)usr.Id into infoUseData
                                  from infoUse in infoUseData.DefaultIfEmpty()
                                  join ins in institutions on infod.Maintenanceint_Id equals (int)ins.Id into insData
                                  from isd in insData.DefaultIfEmpty()
                                  select new
                                  {
                                      lod.Id,
                                      BridgeId = infod.Id,
									  lod.Type,
									  lod.Time,
									  lod.Det_name,
									  lod.DetInstitiution,
									  lod.Result,
									  lod.Consequence,
									  lod.Auditor,
									  lod.Checker,
									  lod.Report_url,
									  lod.Project_name,
									  lod.Archive_lable,
									  infoUse.UserTrueName,
									  bgeName = infod.Name,
									  infod.Maintenanceint_Id,
									  isd.Inst_name
								  }).OrderByDescending(c => c.Time);
								  loadSource.Dump();

image-20211208192927683

这个Linq里面使用了Left Join,所以导致很多空白的数据被过滤出来。

linq代码join查询

void Main()
{
	var tableList=new List<string>(){ "bge_superstructure_info","bge_superstructrue_info_ctn","bge_superstructrue_info_yjl","bge_superstructrue_info_xbl" };
	tableList.Dump();
	var DataList=(from A in bge_dictionars
	join B in bge_dictionary_subs
	on (int)A.Id equals B.Dic 
	where (tableList.Contains(A.Belong_table_name) && B.State==1 )

	select new{ itemId=A.Id,selector_cn_name=A.Name,selector_en_name=A.En_name,drop_down_id=B.Id,drop_down_value=B.Data_name,B.State,remark=A.Belong_table_name}).Dump();
}

// You can define other methods, fields, classes and namespaces here
//对应的csharp代码如下,注意枚举值的处理
//var DataList = await(from A in _bgeDictionarEntity
//					 join B in _begeDictionarySubEntity
//						 on (int)A.Id equals B.Dic
//					 where (tableList.Contains(A.Belong_Table_Name) && (int)B.State == 1)
//					 select new { itemId = A.Id, selector_cn_name = A.Name, selector_en_name = A.En_Name, drop_down_id = B.Id, drop_down_value = B.Data_Name, B.State, remark = A.Belong_Table_Name }
//			  ).ToListAsync();

image-20211228104900473

linq字典数据直接返回Json

image-20211228113247727

void Main()
{
	var tableList=new List<string>(){ "bge_superstructure_info","bge_superstructrue_info_ctn","bge_superstructrue_info_yjl","bge_superstructrue_info_xbl" };
	tableList.Dump();
	var DataList=(from A in bge_dictionars
	join B in bge_dictionary_subs
	on (int)A.Id equals B.Dic 
	where (tableList.Contains(A.Belong_table_name) && B.State==1 )
    group A by A.En_name
    into groupedDemoClass
    select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList()).Dump();
	//select new{ itemId=A.Id,selector_cn_name=A.Name,selector_en_name=A.En_name,drop_down_id=B.Id,drop_down_value=B.Data_name,B.State,remark=A.Belong_table_name}).Dump();
   
	//groupedDemoClass.ToDictionary(d =>d.,d=>d. )
}

// You can define other methods, fields, classes and namespaces here
//对应的csharp代码如下
//var dataList = await(from A in _bgeDictionarEntity
//					 join B in _begeDictionarySubEntity
//						 on (int)A.Id equals B.Dic
//					 where (tableList.Contains(A.Belong_Table_Name) && (int)B.State == 1)
//					 orderby A.En_Name
//					 select new { itemId = A.Id, selector_cn_name = A.Name, selector_en_name = A.En_Name, drop_down_id = B.Id, drop_down_value = B.Data_Name, B.State, remark = A.Belong_Table_Name }
//			   ).ToListAsync();
//var dictObj = from a in dataList
//			  group a by a.selector_en_name
//	into b
//			  select b;
//var dicDto = dictObj.ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

微软官方提供的Linq教程:dotnet-try

image-20211228224442588

项目地址:https://github.com/dotnet/try-samples

运行该项目的时候会遇到坑,正确的使用姿势如下:

dotnet tool uninstall -g dotnet-try
dotnet tool uninstall -g Microsoft.dotnet-try
dotnet tool install -g --add-source "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json" Microsoft.dotnet-try

关键参考信息:https://github.com/dotnet/try/blob/main/DotNetTryLocal.md

image-20211229000945213

PS C:\Users\47664> dotnet tool install -g Microsoft.dotnet-try
You can invoke the tool using the following command: dotnet-try
Tool 'microsoft.dotnet-try' (version '1.0.20474.1') was successfully installed.
PS C:\Users\47664> d:
PS D:\> cd dotnet-try
PS D:\dotnet-try> dotnet tool update -g Microsoft.dotnet-try
Tool 'microsoft.dotnet-try' was successfully updated from version '1.0.20474.1' to version '1.0.21418.2'.
PS D:\dotnet-try>
PS D:\dotnet-try> cd 101-linq-samples
PS D:\dotnet-try\101-linq-samples>

文档信息

Search

    Table of Contents