English 中文(简体)
• 如何将“力量”改为“身份识别器”。
原标题:How to convert a String[] to an IDictionary<String, String>?

如何将<条码>编码改为<条码>。 IDictionary<String, String>?

指数0,2,4,......的数值为关键,因此,指数1,3,5,......的数值为数值。

例:

new[] { "^BI", "connectORCL", "^CR", "connectCR" }

=>

new Dictionary<String, String> {{"^BI", "connectORCL"}, {"^CR", "connectCR"}};
最佳回答
Dictionary<string,string> ArrayToDict(string[] arr)
{
    if(arr.Length%2!=0)
        throw new ArgumentException("Array doesn t contain an even number of entries");
    Dictionary<string,string> dict=new Dictionary<string,string>();
    for(int i=0;i<arr.Length/2;i++)
    {
      string key=arr[2*i];
      string value=arr[2*i+1];
      dict.Add(key,value);
    }
    return dict;
}
问题回答

我建议说,为了清晰起见,应当有好老。 但是,如果你坚持要求准则调查,这项工作应当:

var dictionary = Enumerable.Range(0, array.Length/2)
                           .ToDictionary(i => array[2*i], i => array[2*i+1])

准则准则中确实没有容易做到这一点(即使有,也肯定不会明确意图)。 简便地做到这一点:

// This code assumes you can guarantee your array to always have an even number
// of elements.

var array = new[] { "^BI", "connectORCL", "^CR", "connectCR" };
var dict = new Dictionary<string, string>();

for(int i=0; i < array.Length; i+=2)
{
    dict.Add(array[i], array[i+1]);
}

与此类似:

        string[] keyValues = new string[20];
        Dictionary<string, string> dict = new Dictionary<string, string>();
        for (int i = 0; i < keyValues.Length; i+=2)
        {
            dict.Add(keyValues[i], keyValues[i + 1]);
        }

Edit:C# tag的人很快......

如果您有Rx,作为扶养者,可以:

strings
    .BufferWithCount(2)
    .ToDictionary(
         buffer => buffer.First(), // key selector
         buffer => buffer.Last()); // value selector

<代码>BufferWithCount(int=1/code>>从输入序列中得出第一个<编码>count值,并将其列为清单,然后取下一个count值,等等。 页: 1 然后将第一个清单项目作为关键项目,最后一个项目(两个项目清单=第二个)作为价值。

然而,如果你不使用Rx,你可以使用<代码>的这种执行。 BufferWithCount:

static class EnumerableX
{
    public static IEnumerable<IList<T>> BufferWithCount<T>(this IEnumerable<T> source, int count)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }

        if (count <= 0)
        {
            throw new ArgumentOutOfRangeException("count");
        }

        var buffer = new List<T>();

        foreach (var t in source)
        {
            buffer.Add(t);

            if (buffer.Count == count)
            {
                yield return buffer;
                buffer = new List<T>();
            }
        }

        if (buffer.Count > 0)
        {
            yield return buffer;
        }
    }
}

它像其他人一样,已经打过我,并且(或)有更有效的答案,但我说两点:

选择住所可能是在这种情况下取得最明显成就的途径......

var words = new[] { "^BI", "connectORCL", "^CR", "connectCR" };

var final = words.Where((w, i) => i % 2 == 0)
                 .Select((w, i) => new[] { w, words[(i * 2) + 1] })
                 .ToDictionary(arr => arr[0], arr => arr[1])
                 ;

final.Dump();

//alternate way using zip

var As = words.Where((w, i) => i % 2 == 0);
var Bs = words.Where((w, i) => i % 2 == 1);

var dictionary = new Dictionary<string, string>(As.Count());

var pairs = As.Zip(Bs, (first, second) => new[] {first, second})
                .ToDictionary(arr => arr[0], arr => arr[1])
                ;

pairs.Dump();

这是我最后采用一种做法,作为推广方法加以实施:

internal static Boolean IsEven(this Int32 @this)
{
    return @this % 2 == 0;
}

internal static IDictionary<String, String> ToDictionary(this String[] @this)
{
    if (!@this.Length.IsEven())
        throw new ArgumentException( "Array doesn t contain an even number of entries" );

    var dictionary = new Dictionary<String, String>();

    for (var i = 0; i < @this.Length; i += 2)
    {
        var key = @this[i];
        var value = @this[i + 1];

        dictionary.Add(key, value);
    }

    return dictionary;
}

Pure Linq

  1. Select : Project original string value and its index.
  2. GroupBy : Group adjacent pairs.
  3. Convert each group into dictionary entry.

string[] arr = new string[] { "^BI", "connectORCL", "^CR", "connectCR" };

var dictionary = arr.Select((value,i) => new {Value = value,Index = i})
                .GroupBy(value => value.Index / 2)
                .ToDictionary(g => g.FirstOrDefault().Value, 
                                   g => g.Skip(1).FirstOrDefault().Value);





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签