gpt4 book ai didi

c# - LINQ (C# .NET 4) 中的转换问题

转载 作者:行者123 更新时间:2023-11-30 14:59:49 25 4
gpt4 key购买 nike

我遇到了一个非常令人困惑的问题,我希望有人能帮助我。在我的应用程序中,我有以下数据结构:

public struct EntityDetails
{
public string EntityName { get; set; }
public List<AttributeDetails> Attributes { get; set; }
public bool EntityExists { get; set; }
}

public struct AttributeDetails
{
public string AttributeName { get; set; }
public string DisplayName { get; set; }
public string DataType { get; set; }
public string Description { get; set; }
public bool AttributeExists { get; set; }
}

我使用以下实例化对象:

public static List<EntityDetails> entityList { get; set; }

因此,我需要做的是能够返回基于实体名称和属性名称的过滤后的属性列表。为此,我编写了以下 LINQ 片段:

public static List<AttributeDetails> GetFilteredAttributeList(string pEntityName, string pAttributeFilter)
{



return (List<AttributeDetails>)entityList.Where(e => e.EntityName == pEntityName)
.Select(e => e.Attributes
.Where (a => a.AttributeName
.Contains (pAttributeFilter)));


}

最初,当我执行此操作时,一开始并没有强制转换,但它引发了编译时错误,因此我添加了强制转换以使其能够编译。但是,当涉及到此方法时,我收到以下消息:

{"Unable to cast object of type 'WhereSelectListIterator2[MPYA.BU.CRMClientUpdateTool.CRMAccess.CRMAccessLayer+EntityDetails,System.Collections.Generic.IEnumerable1[MPYA.BU.CRMClientUpdateTool.CRMAccess.CRMAccessLayer+AttributeDetails]]' to type 'System.Collections.Generic.List`1[MPYA.BU.CRMClientUpdateTool.CRMAccess.CRMAccessLayer+AttributeDetails]'."}

现在,从我所做的研究来看,一个是 IEnumerable 类型,另一个是列表,我明白这一点,但我终究无法弄清楚如何转换它,所以它可以接受!我也试过 ToList(),通过扩展方法和其他各种东西来转换它。我还确认数据结构包含正确的数据。

如有任何帮助,我们将不胜感激。

更新

抱歉,但出于某种原因,我无法在 8 小时内回复答案叹息。我听从了大家的建议使用 ToList 现在我得到以下错误:

感谢您到目前为止的回答。在我看来 ToList() 是唯一合乎逻辑的方法,但是当我这样做时,我得到以下编译时错误:

error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.IEnumerable<MPYA.BU.CRMClientUpdateTool.CRMAccess.CRMAccessLayer.AttributeDetails>>' to 'System.Collections.Generic.List<MPYA.BU.CRMClientUpdateTool.CRMAccess.CRMAccessLayer.AttributeDetails>'

当我将鼠标悬停在它上面时,实际的错误消息是“System.ArgumentNullException”。

最佳答案

您可以简单地通过调用 .ToList() 结束您的 LINQ 查询 将结果转换为 List<T> .

要记住的一件事是调用 .ToList()在 LINQ 查询上“实现”它,意味着执行不再是 deferred ;结果现在存储在您的内存中 List<T> .

另外,我相信你想使用 .SelectMany() 子句,而不是 .Select() e.AttributesList<AttributeDetails> .如果你使用 Select() , 它将创建一个 IEnumarable<list<AttributeDetails>> ,每个元素都是您的一个实体的属性。 <强> SelectMany将合并返回的列表并返回 IEnumerable<AttributeDetails> ,这似乎是您想要的。

最终,您想要使用以下内容:

return entityList.Where(e => e.EntityName == pEntityName)
.SelectMany(e => e.Attributes
.Where (a => a.AttributeName
.Contains(pAttributeFilter)))
.ToList();

关于c# - LINQ (C# .NET 4) 中的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213816/

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