Select Many in Rx [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Please any one let me know how the SelectMany operator in Rx works. I don't know more about this operator in Linq either.
Please explain this with the help of a simple example, and also in what occasion we will use this operator in Rx.

SelectMany is just:
source.Select(selector).Merge();
In other words, it selects the source input into a stream of Observables, then flattens each Observable into a stream of results.

SelectMany combines projection and flattening into a single step. Suppose you have a number of lists like { {1, 2}, {3, 4, 5}, { 6, 7 } } you can use SelectMany to flatten it into a single list like: { 1, 2, 3, 4, 5, 6, 7}
SelectMany in Rx can flatten multiple sequences into one observable (there are actually several overloads).
For a practical example, suppose you have a function DownloadFile(filename) which gives you an Observable which produces a value when the file completes downloading. You can now write:
string[] files = { "http://.../1", "http://.../2", "http://.../3" };
files.ToObservable()
.SelectMany(file => DownloadFile(file))
.Take(3)
.Subscribe(c => Console.WriteLine("Got " + c) , ()=> Console.WriteLine("Completed!"));
All 3 observables of DownloadFile are flattened into one, so you can wait for 3 values to arrive to see that all downloads are completed.

I found this short video helpful in understanding SelectMany for Rx (and as a more advanced use of marble diagrams): http://channel9.msdn.com/Blogs/J.Van.Gogh/Reactive-Extensions-API-in-depth-SelectMany

Related

Differences between ways of creating ImmutableList [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
What is the differences between ways of creating ImmutableList?
List<int> numbers = new List<int>(){0, 1, 2, 3};
ImmutableList<int> immutableList = numbers.ToImmutableList();
ImmutableList<int> immutableList = ImmutableList.Create<int>(0, 1, 2, 3);
ImmutableList<int> immutableList = ImmutableList.CreateRange<int>(new List<int>() { 0, 1, 2, 3 });
ImmutableList<int>.Builder builder = ImmutableList.CreateBuilder<int>();
builder.AddRange(new List<int>() { 0, 1, 2, 3 });
ImmutableList<int> immutableList = builder.ToImmutableList();
Which is the faster and usabel?
Let's take a look at how each of those is implemented.
First off, the ToImmutableList() extension method involves first trying to cast to ImmutableList<T>, and then falling back to ImmutableList<T>.Empty.AddRange() otherwise. ImmutableList.Create() and ImmutableList.CreateRange() also call ImmutableList<T>.Empty.AddRange().
Finally, the builder is the only one that has some key difference, although you're using it wrong: you should be using ToImmutable(), because it involves doing fewer unecessary copies. ToImmutableList() just uses the above extension method, and therefore also uses ImmutableList<T>.Empty.AddRange().
Really, if you're building a possibly large immutable list as you go, you should use a builder, and then freeze it with ToImmutable() when you're done modifying it. Otherwise, all the other methods are functionally identical, so pick whichever is clearest to you.

Pairing random items in lists [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to make a program to randomize entries for an event. I have the program working well enough for entering the entries but I'm stuck at randomizing it.
I have 2 lists, let's call one Head and the other one Heel. I have the lists as follows:
Head: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Heel: [1a, 2a, 3a, 4a, 5a, 6a, 7a, 8a, 9a, 10a]
I want each item in the Head to have 2 random partners from Heel, but no value from Heel can be matched more than twice at the end of it all. In the final output, each entry should be listed twice and only twice.
Hopefully someone understands and is able to help me, thanks.
I feel like I need to go take a long bath, I feel so dirty for having this piece of code see the light of day, but something about OP's logic was mezmerizing. Anyway, 3 AM me thinks this should work:
var head = new List<char>("abcdef");
var heel = new List<char>("123456");
heel = heel.Concat(heel);
var randomer = new Random();
foreach (var knownItem in head)
{
var idx1 = randomer.Next(heel.Count);
var pair1 = heel[idx1];
heel.RemoveAt(idx1);
char pair2='\0';
while (true)
{
var idx2 = randomer.Next(heel.Count);
pair2 = heel[idx2];
if (pair2 != pair1)
{
heel.RemoveAt(idx2);
break;
}
}
//DoTheDew
}
Next steps for tomorrow: dieharder test the results of this version vs #Arj
Here's a possible solution. Since there's no code to start with, I've done it in pseudocode for now.
Create two Lists, each having all of the values in heel; call them heel1 and heel2
For each element i in head:
Generate a random number j where 0 <= j < heel1.size. Remove the element at heel1[j] - that's your first pairing
Repeat with heel2 (for a different generated j). Remove that element at heel2[j] - that's the second pairing
Store i along with the two removed values
By the end you will have two numbers for each value in head, with no value from heel appearing more than twice. Since we are removing any used values each time, we don't need to check for your "more than two pairings" rule.

C# How to sort list of objects with string values [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need sort list of string values using IComparable:
10.1, 10.10, 10.11, 10.2, 10.3
Expected result:
10.1, 10.2, 10.3, 10.10, 10.11
Tried to use list.Sort but didn't work
Basically what you want to do is to sort by the number after the decimal point in the string. So, take only that part, convert it to a number and then sort. Using Comparer it will look like
List<string> values = new List<string> { "10.1", "10.10", "10.11", "10.2", "10.3" };
values.Sort((x, y) => int.Parse(x.Split('.')[1]).CompareTo(int.Parse(y.Split('.')[1])));
Or using linq it will look like:
var result = values.OrderBy(value => int.Parse(value.Split('.')[1]));
In the case you want to first sort by the second part and then by the first you can do:
var result = values.OrderBy(value => int.Parse(value.Split('.')[0]))
.ThenBy(value => int.Parse(value.Split('.')[1]))
.ToList();
keep in mind that this solution is naive and assumes all your values have a . and that the 2 parts of it can be parsed into int - If it is not the case then you can use TryParse

How to use Enumerable Methods [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have looked around for some good explanations of these enumerable methods but cant seem to find one that explains it properly.
I have been using a few of them like select,skip,orderby and sort but I don't know how they actually work
For example
string[] RandomNames = names.OrderBy(x => rnd.Next()).ToArray();
or
string[] SelectedNames = names.Select(i => i.ToString()).ToArray()
So there are a few things that I am unclear of:
So what does the => actually do
How would a group by work and what would it be used for.
A brief explanation would be appreciated but an in depth explanation is what I am looking for.
=> is lambda expression.
What is lambda expression and why is so useful? Let's consider example:
You have list of random integers and you want to choose only divided by 2. In normal way it will look like that:
public bool IsDevidedByTwo(int number)
{
if(number % 2 == 0)
return true;
return false ;
}
List<int> DevidedByTwoList = new List<int>;
foreach(var number in RandomIntsList)
{
if(IsdevidedByTwo(number)) DevidedByTwoList.Add(number);
}
It easy an clear but takes lot of space so you can't understand it immediatly especially when function IsDevidedByTwo() will be in diffrent file.
How it will be look like when you use lamba expression and LINQ:
List<int> DevidedByTwoList = RandomIntsList.Where(number => number % 2 == 0).ToList();
One line instead of 12.
number => number % 2==0 is lambda expression. It's check if number is devided by 2. It works exacly like IsDevidedByTwo function but you don't need to name it.
.Where() is LINQ method witch can filter for example list and choose only elements fulfill condition in brackets.
If you want to learn more read something about LINQ and lambda expresions.
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
It Reduces typing. No need to specify the name of the function, its return type, and its access modifier.When reading the code, you don't need to look elsewhere for the method's definition.
Here is a very good article with examples and explanations.
geekswithblogs

How in c# to convert a string of comma-separated bracket-enclosed (nested) comma-separated values into a List of Lists? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given a string like
"(5678, 2, 41, 3), (4852, 8, 3, 97), (4562, 85, 3, 7)"
How in c# can I turn that into a List (or array) of the three parent values, each of which being a List (or array) of its four child values?
I'm thinking that I want to end up with a List<List<int>> if that makes sense.
May not be the best solution but it will work. Here is the code:
string value = "(5678, 2, 41, 3), (4852, 8, 3, 97), (4562, 85, 3, 7)";
var result = value
.Split(')')
.Select(i => i.Replace('(', ' '))
.Select(i => i.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList()).ToList();
I would use a regex to split the string up into (p1), (p2), (p3) and then a simple string.Split() to access to the child values for each parent.

Categories

Resources