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: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: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);
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: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: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])
Source: stackoverflow.com
Related Query
- How to convert a string to C# code in the SELECT of C# LINQ
- How to Convert the value in DataTable into a string array in c#
- How can I convert DateTime to String in Linq Query?
- How to convert string to DateTime in C# EF Core query
- How to convert a list of ints to a string array in Linq?
- How can i convert IQueryable<string> to a string array?
- How to use ToString() method to convert an integer to string inside LINQ
- how to convert int to string in Linq to entities
- How might I convert this SQL code to LINQ?
- How do i convert this linq code to inline sql
- How to convert SQL timestamp to a string in Entity Framework?
- How to convert two columns into a single string column with dynamic linq?
- How to convert List to a string and back
- How to convert an IOrderedEnumerable<char> to string in c#?
- How to convert a string to decimal in a LINQ query
- How to convert string array to string in Linq to entities?
- How to convert this recursive code to Linq
- How to implicitly convert Byte[] to string when building model inside the controller
- How do you implicitly convert a string value to an enumeration using LinqToSql?
- How to convert this code to LINQ?
- How can I convert string into int without enumerating a query
- How to convert a String line to class
- How to convert a String to TimeSpan inside a Linq Expression?
- Dynamic Linq using Data Objects. How to convert Int32 to String for purpose of calling String.Contains()
- How to convert xelement to a string in c#?
- How to convert csv file's specific column to string List
- How do I convert a string array(having xml content) into an XML file?
- How to Convert a search string into a LINQ Query?
- Linq - how to convert this code to linq
- How to convert List of <Entities> to one string with grouping?
More Query from same tag
- Populating a C# / XAML combobox using EF and LINQ
- Linq ISNULL functionality
- Proper way to query DataContext using Group by that has fields with Nulls
- Is there any way to use OData $orderby on complex type?
- LINQ building array with multiple values per select
- Filtering nested lists with nullable property
- Get data of multiple column with same foreign key in C# LINQ
- optimize linq query with multiple include statements
- Select a List inside a List and add an item to it for JSON
- Nhibernate - Database side queries
- Linq related table not queryable error
- How to get Data form List<Object> in Entity Framework
- LINQ, Lambda, confused
- ASP.NET MVC - Sorting forum threads depending on last post
- table to xml record c#
- WEB API Sequence contains no elements
- Update values in ConcurrentDictionary<string, Tuple<string, string>>
- how to update record with linq
- query subcollection when key and value are different subcollections - linq
- IEnumerable<T>.Contains with predicate
- C# Ternary operator ?: efficiency
- Sorting Array based on property of object on inner array
- xml to linq, how to fix late binding?
- Linq2SQl eager load with multiple DataLoadOptions
- Cannot access Table in converted query (plain SQL to LINQ)
- c# linq to xml take one element of many
- LINQ lambda with where clause
- DataContext.ExecuteQuery parameter issues
- LINQ to SQL and field concatenation in SQL
- What is after LINQ?