gpt4 book ai didi

c# - 重构 Linq 查询

转载 作者:行者123 更新时间:2023-11-30 19:56:42 25 4
gpt4 key购买 nike

我有一个 LINQ 查询,我正在尝试最小化,但在我尝试时出现错误。Genkai_db 是一个 Entity Framework 实例,我查询 sql 表。

这是有效的:

public UNITY_DB_PRODEntities12 Genkai_db = new UNITY_DB_PRODEntities12();


public List<string[]> Query_FpacInactif()
{
List<string[]> li = new List<string[]>();
List<string> u = Genkai_db.final_full_data
.Where(x => x.FPAC_TimeStamp > 100)
.Select(x => x.computername)
.ToList<string>();
foreach (string a in u)
{
string[] Sarray = new string[] { a, "FPAC" };
li.Add(Sarray);
}

return li;
}

在另一个类似的函数中,我试图重构为一行:

public List<string[]> Query_McAfeeConsolidation()
{
List<string[]> li = (Genkai_db.Consolidation_McAfee
.Select(x => new string[] { x.computername, "McAfee" }))
.ToList();
return li;
}

最后一个函数因错误而失败:

Unable to initialize the array of type 'System.String []' in a query result. Use 'System.Collections.Generic.List`1 [System.String]' instead.

PS:在询问甚至使用 List<string> 之前,我尝试了很多东西在 string[]但是一行中没有任何效果。

最佳答案

我猜它无法将其转换为 SQL 查询,您可以使用 AsEnumerable 和项目将其恢复到内存中。

根据您的原始查询,您始终可以过滤 SQL 中的记录,之前的查询将整个数据加载到内存中,这显然不好(但根据您的 Query_McAfeeConsolidation 方法编写):-

 List<string[]> li = Genkai_db.Consolidation_McAfee
.Where(x => x.FPAC_TimeStamp > 100)
.Select(x => x.computername)
.AsEnumerable()
.Select(x => new string[] { x, "McAfee" }))
.ToList();

关于c# - 重构 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33039855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com