c# - 将泛型 IEnumerable<T> 转换为 IEnumerable<KeyValuePair> (C#)

标签 c# .net generics code-reuse

在下面的代码中,我需要明确提及 CountryIdCountryName 但我想避免这种情况并尝试创建一个通用方法.

public struct KeyValueStruct
{
    public int Key { get; set; }
    public string Value { get; set; }
}

private static IEnumerable<KeyValueStruct> ConvertPocoToKeyValueList(IEnumerable<CountryPoco> list)
{
    var result = new List<KeyValueStruct>();

    if (list != null)
    {
        foreach (var item in list)
        {
            result.Add(new KeyValueStruct()
            {
                Key = item.CountryId,
                Value = item.CountryName
            });
        }
    }

    return result;
}

我从列表中知道第一个属性始终是整数(在本例中是 CountryId),第二个属性是字符串。

我正在考虑使用 Generics 来实现,但我不确定这是不是最好的方法,请参阅我建议的代码(虽然它不起作用)。

private static IEnumerable<KeyValueStruct> ConvertPocoToKeyValueList<T>(T list) 
{
    var result = new List<KeyValueStruct>();

    if (list != null)
    {
        foreach (var item in list)
        {
            result.Add(new KeyValueStruct()
            {
                Key = item.CountryId,
                Value = item.CountryName
            });
        }
    }

    return result;
}

如果你有更好的想法来达到相同的结果,那么请提出。

最佳答案

您可以通过传递用作键和值的属性来使其通用。我认为使用通用的 struct名为 KeyValuePair<Tkey, TValue>比自己重新发明轮子更好:

private static IEnumerable<KeyValuePair<Tkey, TValue>> 
                       ConvertPocoToKeyValueList<TSource, Tkey, TValue>
                                    (IEnumerable<TSource> list,
                                     Func<TSource, Tkey> keySelector,
                                     Func<TSource, TValue> valueSelector)
        {
            return list.Select(item => new KeyValuePair<Tkey, TValue>
                                          (keySelector(item), valueSelector(item)));
        }

用法:

var result = ConvertPocoToKeyValueList(list, x=> x.CountryId, x=> x.CountryName);

您甚至可以通过直接使用而无需使用此通用方法来做到这一点:

var result = list.Select(item => new KeyValuePair<Tkey, TValue>
                                              (item.CountryId, item.CountryName));

关于c# - 将泛型 IEnumerable<T> 转换为 IEnumerable<KeyValuePair> (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933627/

相关文章:

c# - 在 Lambda 中实现 "where in"子句?

generics - 如何在 Kotlin 中将 TypeToken + 泛型与 Gson 一起使用

c# - 如果两者都存在,如何调用Foo(此对象o)而不是Foo(此T t)?

.net - 性能关键的 GUI 应用程序(windows、linux)

c# - 以编程方式添加 span 标记,而不是 Label 控件?

c# - 压缩小字符串,用什么创建外部字典?

c# - List<T> 和 ArrayList<T> 哪个更快?

c# - 无法从泛型类型转换为接口(interface)

c# - 在 RichTextBox C# WPF 中设置插入符位置

c# - 如何让 OleDb 代码异步运行?