First list:
a=[0,1,2,3,4]
Second list:
b=[4.233,5.2324,6.342,3.233,8.435]
Is there any way to merge these two lists into a json object?
Ex: object: [{"a":0,"b":4.233},{"a":1,"b":5.2324},{"a":2,"b":6.342},{"a":3,"b":3.233},{"a":4,"b":8.435}]
Assuming you're working server side and have two arrays a and b,
var a = new[] {0, 1, 2, 3, 4};
var b = new[] {4.233, 5.2324, 6.342, 3.233, 8.435};
var c = a.Zip(b, (ai, bi) => new{a = ai, b = bi});
At this point, JsonConvert.SerializeObject(c) will output the example JSON you provided. You will need JSON.Net.
Zip() takes the nth element of both lists, and allows you to apply a function to each combination.
Related
An array in .Net is a reference type.
Given the two code segments above.
Question: why setting value varible "fixedItem" affects varible "data" in the first segment code, but the second segment code is does not affects
First code segment:
var data = new List<IList<int>>();
data.Add(new List<int>() { 1, 2, 3 });
data.Add(new List<int>() { 3, 8, 6,5 });
data.Add(new List<int>() { 1, 2 });
var fixedItem = data.Last();
fixedItem[1] = 8;
//Result:
//data = {{1,2,3}, {3,8,6,5}, {1,8}}
Second code segment:
var data = new List<IList<int>>();
data.Add(new List<int>() { 1, 2, 3 });
data.Add(new List<int>() { 3, 8, 6,5 });
data.Add(new List<int>() { 1, 2 });
var fixedItem = data.Last().ToArray();
fixedItem[1] = 8;
//Result:
//data = {{1,2,3}, {3,8,6,5}, {1,2}}
docs
according to documentation list.ToArray() method returns array with copies of original list
With the first version, fixedItem is the last item from the outer list, i.e. the third inner list. The same instance. Changing that list will be visible everywhere that list is referenced.
However, in the second version you use ToArray(), which creates a separate copy of the list contents, in a vector. You can do anything you like with your isolated copy - it is a different collection instance (and different collection type). Changing it will only be visible to things that reference the copy. The original list is unaffected because it is a different collection.
This is because with ToArray method, you have created a copy of the original list.
Official documentation
Copies the elements of the List to a new array.
There are many thing involve over here.
When you do ToArray in second segment , it actually create new variable and new collection.
Here you have created list of int, in this integer is value type so when it create new collection it copies those value and assign new memory location.
Now instead of int if you have created some reference type like object of class then if you change value over in one collection affect other. Here variable is new but it still reference the same memory location.
Look at the data types you've created after using Last() from Linq.
You receive two very different data types.
One would be a list while the other is just int[]. They have fairly different functionalities and ways to represent and handle data.
I am writing a program where I need to swap values from nested list.
Here is what I am looking for example:
Let's say I have a List<object[]> where these list contains two rows as below:
{"id1", "id2", "id3"}, {1,2,3}
Now I want to make it like below:
{"id1", 1}, {"id2", 2}, {"id3", 3}
How can I do that in C#?
Hopefully I have cleared my point.
With 2 input sequences, this can be treated as a "zip" operation:
List<object[]> list = new List<object[]>
{
new object[] {"id1", "id2", "id3" },
new object[] {1,2,3},
};
var rotated = Enumerable.Zip(list[0], list[1],
(x, y) => new object[] { x, y }).ToList();
Note I would advise against using lots of object[] etc here. There's almost always a better way to represent the data.
With an arbitrary number of input sequences, this would need to be done as a "transpose" operation.
Is there a simple lambda expression to extract elements from one list and put them into another? without LINQ?
for example to map, a source list of elements T to another list (or return a list) with the string name for each element in the source.
Update...with pseudocode.
List<int> intList = new List<int>() { 1, 2, 3};
List<string> stringList = new List<string>(intList.ToArray((i) => intList[i].ToString())); // this doesn't work obviously
stringList should be {"1", "2", "3"}
List<T>.ConvertAll() provides a straightforward way to change types without LINQ.
In your case...
List<string> stringList = intList.ConvertAll(i => i.ToString());
I have a list as follows:
{CT, MA, VA, NY}
I submit this list to a function and I get the optimum waypoint order list
{2,0,1,3}
Now I have to rearrange the list as per the order that is newly provided. i.e. after rearranging, the list should look like:
{VA, CT, MA, NY}
What is the optimum way to do it? Using linq is there a way?
You could try the following:
var list = new List<string>{"CT", "MA", "VA", "NY"};
var order = new List<int>{2, 0, 1, 3};
var result = order.Select(i => list[i]).ToList();
This seems like the simplest approach:
oldItems = LoadItems(); //{"CT","MA","VA","NY"};
List<string> newItems = List<string>();
foreach(int idx in returnedIndexes)
{
newItems.Add(oldItems[idx]);
}
I have two arrays, x and y, where y is the value of the tens of every element in x. Now, I want to sort y. But, the order of y will be different of x's. So, I can't tell after sorting which element in y was related to, for instance, x[0].
I want a "double sorting" maybe.
Array.Sort has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys array:
int[] keys = { 1, 4, 3, 2, 5 };
string[] items = { "abc", "def", "ghi", "jkl", "mno" };
Array.Sort(keys, items);
foreach (int key in keys) {
Console.WriteLine(key); // 1, 2, 3, 4, 5
}
foreach (string item in items) {
Console.WriteLine(item); // abc, jkl, ghi, def, mno
}
So in your case, it sounds like you want:
Array.Sort(y,x); // or Sort(x,y); - it isn't 100% clear
How about?
var selectedArr = new int[] { 1, 3, 5, 7, 9 };
var unorderArr = new int[] { 9, 7, 5, 3, 1 };
var orderedArr = unorderArr.OrderBy(o => selectedArr.IndexOf(o));
If we have two arrays of complex objects and want to sort them according to one of the two arrays then we can use the next approach:
// We want to sort "people" array by "Name" and
// accordingly to it reorder "countries" array.
Person[] people = new Person[]
{
new Person {Name = "Fill"},
new Person {Name = "Will"},
new Person {Name = "Bill"},
};
Country[] countries = new Country[]
{
new Country {Name = "Canada"},
new Country {Name = "UK"},
new Country {Name = "USA"}
};
// Here we sort "people" array, but together with each "Person"
// in sorted array we store its "index" in unsorted array. Then we
// will use this "index" to reorder items in "countries" array.
var sorted = people
.Select((person, index) => new {person, index})
.OrderBy(x => x.person.Name)
.ToArray();
// Here "people" array is sorted by "Name", and
// "contries" array is reordered accordingly to it.
people = sorted.Select(x => x.person).ToArray();
countries = sorted.Select(x => countries[x.index]).ToArray();
Another approach is to use overload of the method Array.Sort with IComparer. At first we should implement IComparer:
private class PeopleComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
}
}
And then we can sort two our arrays:
Array.Sort(people, countries, new PeopleComparer());
Here is complete sample that demonstrates these two approaches.
If y is always the tens value of x, y probably shouldn't exist - you should probably just calculate it's value directly off of x when needed.
In general, sorting parallel arrays is only possible (without hand rolling a sort algorithm) when the sort algorithm takes a custom "swap" function, which you can implement in terms of swapping elements in both arrays simultaneously. std::sort in C++ and qsort in C don't allow this.
Also in the general case, consider a single array where the element is a pair of items, rather than a parallel array for each item. This makes using "standard" algorithms easier.