score:8
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;
}
score:6
There's really no easy way to do this in LINQ (And even if there were, it's certainly not going to be clear as to the intent). It's easily accomplished by a simple loop though:
// 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]);
}
score:11
I'd recommend a good old for loop for clarity. But if you insist on a LINQ query, this should work:
var dictionary = Enumerable.Range(0, array.Length/2)
.ToDictionary(i => array[2*i], i => array[2*i+1])
score:3
Something like this maybe:
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: People in the C# tag are damn fast...
score:0
It looks like other people have already beaten me to it and/or have more efficient answers but I'm posting 2 ways:
A for loop might be the clearest way to accomplish in this case...
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();
score:0
FYI, this is what I ended up with using a loop and implementing it as an extension method:
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;
}
score:1
If you have Rx as a dependency you can do:
strings
.BufferWithCount(2)
.ToDictionary(
buffer => buffer.First(), // key selector
buffer => buffer.Last()); // value selector
BufferWithCount(int count)
takes the first count
values from the input sequence and yield them as a list, then it takes the next count
values and so on. I.e. from your input sequence you will get the pairs as lists: {"^BI", "connectORCL"}, {"^CR", "connectCR"}
, the ToDictionary
then takes the first list item as key and the last ( == second for lists of two items) as value.
However, if you don't use Rx, you can use this implementation of 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;
}
}
}
score:0
Pure Linq
- Select : Project original string value and its index.
- GroupBy : Group adjacent pairs.
- 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);
Source: stackoverflow.com
Related Articles
- List or Array of String Contain specific word in Html Source Code
- How to convert a string to C# code in the SELECT of C# LINQ
- Convert string[] to int[] in one line of code using LINQ
- C# - code to order by a property using the property name as a string
- Convert string to int array using LINQ
- Shortest method to convert an array to a string in c#/LINQ
- Convert XElement to string
- Using LINQ to convert a list to a CSV string
- Given a Member Access lambda expression, convert it to a specific string representation with full access path
- Convert datetime to a formatted string inside a LINQ-to-entities query
- Best way to convert Dictionary<string, string> into single aggregate String representation?
- AutoMapper and convert a datetime to string
- Convert String to Int in EF 4.0
- Fastest way to convert string array to double array?
- Convert a list<int> to a joined string of ints?
- Convert linq query to string array - C#
- How to Convert the value in DataTable into a string array in c#
- Convert Array of Strings to Comma Separated String with additional concatenation
- Convert string to int in an Entity Framework linq query and handling the parsing exception
- LINQ Query to Convert string to datetime
- How can I convert DateTime to String in Linq Query?
- convert string to DateTime in linq query with where clause?
- Convert string to decimal in group join linq query
- Convert OData to sql string
- XmlSerializer Convert C# object to xml string
- best way to convert collection to string
- LINQ lambda - convert int to string
- convert int to string in linq for searching
- Convert string array to custom object list using linq
- Easiest way to convert list to a comma separated string by a Specific Property?
- Using if else statement in Linq Query
- Don't take last record in linq C#
- Linq for mapping table
- Select specific columns for Linq group by
- Wrong SQL statements being generated when using System.Data.SQLite.Linq
- WHERE clauses in JOIN using LINQ with lambdas
- Duplicate Entries in many to many table when trying to update an object from EF CodeFirst
- Unable to step into or break in method called inside Linq query/expression
- How to combine Where clause and group by in LINQ
- c# groupby orderby thenby Try specifying the type arguments explicitly
- LINQ to XML: suppressing redundant namespace attribute in child nodes
- How/ could you rewrite this as Linq?
- Fluent and Query Expression — Is there any benefit(s) of one over other?
- C# LINQ Take limited results per grouped
- Casting a nullable in where clause in LinQ-to-entity without null-check
- ModelState is Invalid for Drop Down List
- How to create a nested (parent-Child ) JSON response in c#?
- Grouping data with Linq or not possible?
- How to access different XML nodes which have same parent?
- How to select a nested object with EF Core and Linq?