Skip to main content
 首页 » 编程设计

c#之配置元素集合 LINQ

2024年02月06日27虾米姐

我对 LinQ 有一些疑问。如何在查询或某些 LinQ 条件下按名称获取 ID?这是尝试得到:

var section = ConfigurationManager.GetSection("jobSection"); 
 
if (section != null) 
{ 
    var jobs = (section as JobSection).Jobs; 
    var item = from JobElement je in jobs where je.Name == "Job Name A" select je.Id; 
    Console.WriteLine(item.ToString()); 
} 

这是配置。

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
        <section name="jobSection" type="ConsoleApplication2.JobSection, ConsoleApplication2" /> 
    </configSections> 
    <jobSection> 
        <jobs> 
            <job id="1" name="Job Name A" /> 
            <job id="2" name="Job Name B" /> 
        </jobs> 
    </jobSection> 
</configuration> 

但这是输出:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[ConsoleApplication2.JobElement,System.Int32]

请您参考如下方法:

问题

当然可以 - 您正在打印 Enumerable

由于在通用接口(interface)上没有 ToString 的默认实现,它只打印类型名称 - 这就是您得到奇怪答案的原因。

基本解决方案:foreach

var section = ConfigurationManager.GetSection("jobSection"); 
if (section != null) 
{ 
    var jobs = (section as JobSection).Jobs; 
    var query =  
       from JobElement je in jobs  
       where je.Name == "Job Name A"  
       select je.Id; 
 
    foreach(var item in query) 
       Console.WriteLine(item.ToString()); 
} 

如果将 query 视为一种惰性数组/列表有助于将其视为一种惰性数组/列表 - 它只是在等待您将其项拉出。

只需要一个元素?

顺便说一下 - 也许您希望得到一个结果。在这种情况下,您可以像这样使用 .Single:

var section = ConfigurationManager.GetSection("jobSection"); 
if (section != null) 
{ 
    var jobs = (section as JobSection).Jobs; 
    var query =  
       from JobElement je in jobs  
       where je.Name == "Job Name A"  
       select je.Id; 
    var item = query.Single(); 
    Console.WriteLine(item.ToString()); 
} 

如果结果中没有一个元素,这将抛出异常。备选方案是:

  • .First(会给你第一个元素,如果没有则抛出)
  • .FirstOrDefault(将为您提供第一个元素或默认值 - 如果没有项目,很可能是 null)

重载/linq 的一些乐趣

如果你更深入地研究重载,你会发现你可以像这样组合 Where 和 First(等)部分:

var section = ConfigurationManager.GetSection("jobSection"); 
if (section != null) 
{ 
    var jobs = (section as JobSection).Jobs; 
    var item = jobs.Cast<JobElement>() 
                   .First(je => je.Name == "Job Name A"); 
    Console.WriteLine(item.Id); 
} 

玩得开心