Difficulties retrieving List<int> within List<List<int>> - c#

I am having trouble with the below code:
foreach (var result in results)
{
foreach (int individualresult in result)
{
//Operation
}
}
'results' is a List<List<int>> and I am trying to retrieve each integer from each list within the 'results' list of lists (sorry if that's confusing), however when I run the code no errors are received but it doesn't get any further than the first line.
I've put it in a 'try catch' and it doesn't pick up any exceptions or errors so I am flummoxed as to why it isn't working. Additionally I have tried changing var to List<int> but that didn't change anything either.
Any and all help will be appreciated. Thanks

Try this code in a Console-Application and check the Output. I assume that ether your results is empty or that each individual List in your results is empty.
Console.WriteLine("Start");
if (results == null || !results.Any())
Console.WriteLine("No result received!");
foreach (var result in results)
{
Console.WriteLine("new result-set");
if (result == null || !result.Any())
Console.WriteLine(" Result: Empty list!");
foreach (var individualresult in result)
{
Console.WriteLine(" Result: " + individualresult);
}
}
Console.WriteLine("End");
Console.Readline();

See this example it might help you
class Program
{
static void Main(string[] args)
{
List<int> list1d = new List<int>();
List<List<int>> list2d = new List<List<int>>();
for (int i = 0; i < 10; i++)
{
list1d = new List<int>();
for (int j = 0; j < 10; j++)
{
list1d.Add(i * j + i);
}
list2d.Add(list1d);
}
foreach (var result in list2d)
{
foreach (var i in result)
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}

Related

Arraylist item does not take a string as an input error code : CS0029

ArrayList a = new ArrayList();
a[i] = txtSifre.Text; //ERROR CS0029
I want to store the string data that is coming from a textbox into an ArrayList. However, I face with an convertion error : cannot implicitly convert type 'string' to 'system.collections.arraylist' in C#
Here is the FULL code :
int i = 0;
ArrayList a = new ArrayList();
private void btnEkle_Click(object sender, EventArgs e)
{
Hashtable openwith = new Hashtable();
openwith.Add(txtKullaniciAdi.Text, txtSifre.Text);
foreach (var item in openwith)
{
foreach (DictionaryEntry de in openwith)
{
listBox1.Items.Add($"User Name : {de.Key} \t Password : {de.Value}");
}
}
a[i] = txtSifre.Text; //ERROR CS0029 !!
if(i>=1)
{
for (int J = 1; J < 2; J++)
{
if (a[J - 1].ToString() == a[J].ToString())
{
MessageBox.Show("You can not enter the same password again!!");
}
}
}
i++;
}
}
As Martheen mentions, it would be better to use List.
Example:
var a = new List<string>();
a.Add(txtSifre.Text);
However, I will concern myself with certain points as well.
1. Double foreach on openwith
I think the first loop is useless, you can delete it, without deleting its content of course.
//foreach (var item in openwith) //DELETE THIS
//{
foreach (DictionaryEntry de in openwith)
{
listBox1.Items.Add($"User Name : {de.Key} \t Password : {de.Value}");
}
//}
2. If/Foreach block
if(i>=1)
{
for (int J = 1; J < 2; J++)
{
if (a[J - 1].ToString() == a[J].ToString())
{
MessageBox.Show("You can not enter the same password again!!");
}
}
}
It seems quite complex to me for not much, but it is possible that I do not understand all of what you are trying to do.
Here I will give you more suggestions:
You can use List.Count property to count the number of items in a list.
Example: if (a.Count > 1) { ... }
You can use List.Contains method for check if item is in the list.
Example: if (a.Contains(txtSifre.Text)) { ... }
Hoping to have helped you.

Array of string management

I have an array of string, I want to take all the string in an interval of this array until string does not contains something.
Something like:
string [] arrayReading = {
"e","x","a","takefromhere",
"keeptaking","keeptaking","dont'ttakefromhere","m","p","l","e"
};
I have tried:
List<string> result = null;
for (int i = 0; i < arrayReading.Length; i++)
{
if (arrayReading[i].Contains("takefromhere"))
{
result.Add(arrayReading[i]);
if (!arrayReading[i + 1].Contains("dont'ttakefromhere"))
{
result.Add(arrayReading[i + 1]);
if (!arrayReading[i + 2].Contains("dont'ttakefromhere"))
{
rescription.Add(arrayReading[i + 1]);
}
}
}
}
Seems working but it's not really dynamic as I want it, because maybe I need to take 20 values between "takefromhere" and "don'ttakefromhere".
When querying you can try Linq:
using System.Linq;
...
List<string> result = arrayReading
.SkipWhile(item => item != "takefromhere")
.TakeWhile(item => item != "dont'ttakefromhere")
.ToList();
Or if you want good old loop solution:
List<string> result = new List<string>();
bool taking = false;
foreach (string item in arrayReading) {
if (!taking)
taking = item == "takefromhere";
if (taking) {
if (item == "dont'ttakefromhere")
break;
result.Add(item);
}
}
Let's have a look:
Console.Write(string.Join("; ", result));
Outcome:
takefromhere; keeptaking; keeptaking

How to store,sort integers in a List (input from users)?

Just trying to sort out int user inputs (eg 2,21,1 etc)with no luck!
What I am doing wrong?
Console.WriteLine("Could you please insert a few numbers?");
var input = Console.ReadLine();
var numbers = new List<int>();
foreach (var item in input.Split(','))
{
numbers.Add(Convert.ToInt32(item));
numbers.Sort();
Console.WriteLine(item);
}
}
}
}
I think you are trying to input, then sort, and then display.
Console.WriteLine("Could you please insert a few numbers?");
var input = Console.ReadLine();
var numbers = new List<int>();
foreach (var item in input.Split(','))
{
numbers.Add(Convert.ToInt32(item));
}
numbers.Sort();
foreach (int item in numbers)
{
Console.WriteLine(item);
}

Comparing the data

I am trying to compare a set of integers (say alpha) with the result i am getting (say result)
if result is in alpha i should be able to get the output as mentioned in example below
alpha = 0,1,2,3,4,5,6,7
result = 0,5,6
Final answer should be ABBBBAAB
and what i am getting is ABBBBBBB BBBBBABB BBBBBBAB
As per code
public static int[] alpha = new int[8]
{
0,1,2,3,4,5,6,7
};
public static void Main(string[] args)
{
// Lines of code
foreach (var jagged in manager.JaggedList)
{
// Lines of code
foreach (var item in Items)
{
Console.Write(item.Number); //For Ex output here is (0,5,6)
List<int> result = new List<int>();
result.Add(item.Number);
foreach (var Var in result)
{
for (int i = 0; i < alpha.Length; i++)
{
if (result.Contains(alpha[i]))
{
Console.Write(alpha[A]);
}
else
{
Console.Write(alpha[B]);
}
}
}
Console.WriteLine();
}
}
Final answer should be ABBBBAAB
and what i am getting is ABBBBBBB BBBBBABB BBBBBBAB
If Linq is acceptable then just use
alpha
.Select(a => result.Contains(a) ? "A" : "B")
.ToList()
.ForEach(x => Console.Write(x));
using foreach loops
foreach(var a in alpha) {
var found = false;
foreach(var r in result) {
if(a == r) {
found = true;
}
}
Console.Write(found ? "A" : "B");
}

Getting weird result while using Task Parallel Library?

I am trying to do some filter task using TPL. Here I am simplifying the code to filter number based on condition. Here is the code.
public static void Main (string[] args)
{
IEnumerable<int> allData = getIntData ();
Console.WriteLine ("Complete Data display");
foreach (var item in allData) {
Console.Write(item);
Console.Write(" | ");
}
Console.WriteLine ();
filterAllDatas (ref allData, getConditions ());
foreach (var item in allData) {
Console.Write(item);
Console.Write(" | ");
}
Console.WriteLine ();
}
static void filterAllDatas(ref IEnumerable<int> data, IEnumerable<Func<int,bool>> conditions)
{
List<int> filteredData = data.ToList ();
List<Task> tasks = new List<Task>();
foreach (var item in data.AsParallel()) {
foreach (var condition in conditions.AsParallel()) {
tasks.Add(Task.Factory.StartNew(() => {
if (condition(item)) {
filteredData.Remove(item);
}
}));
}
}
Task.WaitAll(tasks.ToArray());
data = filteredData.AsEnumerable ();
}
static IEnumerable<Func<int,bool>> getConditions()
{
yield return (a) => { Console.WriteLine("modulo by 2"); return a % 2 == 0;};
yield return (a) => { Console.WriteLine("modulo by 3"); Thread.Sleep(3000); return a % 3 == 0;};
}
static IEnumerable<int> getIntData ()
{
for (int i = 0; i < 10; i++) {
yield return i;
}
}
Here, it is simple code to filter out integer which is divided by two or three. Now, if I remove that thread sleep code work perfectly but if I put that it is not.
Normally means without Thread.Sleep , both condition execute 10 times e.g. for every number. But if I add Thread.Sleep first condition executes 7 times and second executes thirteen times. And because of this few number skip the condition. I try to debug but didn't get anything that can point out issue with my code.
Is there any good way to achieve this? Like filter condition on data can work async and parallel to improve performance ?
Code is for demo purpose only.
FYI: Currently I am using Mono with Xamarine studio on windows machine.
Please let me know if any further details needed.
I would guess it has to do with how your task's lambda closes over the loop variable condition. Try changing it as follows:
foreach (var condition in conditions.AsParallel()) {
var tasksCondition = condition
tasks.Add(Task.Factory.StartNew(() => {
if (tasksCondition(item)) {
filteredData.Remove(item);
}
}));
Note you're also closing over the loop variable item, which could cause similar problems.
First you can change your getConditions method to see what's happening inside :
static IEnumerable<Func<int, bool>> getConditions()
{
yield return (a) => { Console.WriteLine(a + " modulo by 2"); return a % 2 == 0; };
yield return (a) => { Console.WriteLine(a + " modulo by 3"); Thread.Sleep(3000); return a % 3 == 0; };
}
And if you stop capturing the foreach's variables, it will work :
static void filterAllDatas(ref IEnumerable<int> data, IEnumerable<Func<int, bool>> conditions)
{
List<int> filteredData = data.ToList();
List<Task> tasks = new List<Task>();
foreach (var item in data.AsParallel())
{
var i = item;
foreach (var condition in conditions.AsParallel())
{
var c = condition;
tasks.Add(Task.Factory.StartNew(() =>
{
if (c(i))
{
filteredData.Remove(i);
}
}));
}
}
Task.WaitAll(tasks.ToArray());
data = filteredData.AsEnumerable();
}

Categories

Resources