gpt4 book ai didi

c# - 使用 Linq 查询丢失 foreach

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:01 24 4
gpt4 key购买 nike

我想知道是否可以(如果可能)用 LINQ 查询替换此 foreach:

在线围栏:https://ideone.com/PQEytf

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
public static void Main()
{
// dummy inputs for test sake
var keys = new[] { "key1", "key2" };

var services = new Dictionary<string, Service>
{
{"key1", new Service {Components = new Dictionary<string, string> {{"comp1", "value1"}}}},
{"key2", new Service {Components = new Dictionary<string, string> {{"comp2", "value2"}}}}
};


var serviceComponents = GetServiceComponents(keys, services);
// do something with it
}

public static IEnumerable<ServiceComponent> GetServiceComponents(string[] keys, Dictionary<string, Service> services)
{
var serviceComponents = new List<ServiceComponent>();

// this is the foreach that I want to lose
foreach (
var key in
keys.Select(
name =>
services.FirstOrDefault(
x => x.Key.Equals(name))))
{
serviceComponents.AddRange(key.Value.Components.Select(component => new ServiceComponent
{
Name = key.Key,
Service = component.Key,
Value = component.Value,
}));
}

return serviceComponents.ToArray();

}
}

public class Service
{
public Dictionary<string, string> Components { get; set; }
}

public class ServiceComponent
{
public string Name { get; set; }
public string Service { get; set; }
public string Value { get; set; }
}

最佳答案

是的,您正在寻找的是SelectMany。这允许您将序列中的每个项目转换为另一个序列,然后将所有这些序列展平为一个序列。 (通过将所有序列放入列表中,您可以完成相同的事情,而无需延迟执行。)

return keys.SelectMany(name => services.FirstOrDefault(x => x.Key.Equals(name))
.Value.Components
.Select(component => new ServiceComponent
{
Name = name.Key,
Service = component.Key,
Value = component.Value,
}))
.ToArray();

话虽如此,此查询所做的是获取您的每个键,使用线性搜索在服务中找到相应的项目,然后映射结果。无需使用 FirstOrDefault 进行线性搜索,您可以使用字典的 native 功能有效且高效地查找每个键的值:

return keys.SelectMany(key => services[key].Components
.Select(component => new ServiceComponent
{
Name = key,
Service = component.Key,
Value = component.Value,
}))
.ToArray();

关于c# - 使用 Linq 查询丢失 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414074/

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