- Csharp c create list from multiple lists
- Creating new list out of two lists in c#
- Split List into Multiple Lists by Criteria c#
- How to add to a List while using Multi-Threading?
- Csharp c initialize list of lists
- List array initialization c#
- Inline Initializing C# Lists
- Creating a List of given size, all initialized to some value, in C#
- C# Lists: initialize with size, why then can't use [] access until after .Add()?
- Using And Looping Over a List of Lists – C#
Csharp c create list from multiple lists
First you create new list of type , then loop over your Person list, and for every person you check if age is the same as one in your age list. THEN you can actually iterate the list once except for times, like so: And if the list might contain duplicate numbers and you want to remove 4 in a way that not a single 4 will exist, then you need to do:
Creating new list out of two lists in c#
This looks like exactly what you need.
How to: Find the Set Difference Between Two Lists (LINQ):
List existingList = new List() < 1, 2 >; List modifiedList = new List() < 1, 3 >; var usersToDelete = existingList.Except(modifiedList).ToList(); //contains '2' var usersToAdd = modifiedList.Except(existingList).ToList(); //contains '3'
If you know that it is 1,2,3 and you know you want it 1,4 — then you can just RemoveAt(2) to remove 3, and then set [1] to 4 to change 2 into a 4. RemoveAt is faster than Remove, because it goes by index.
var list = new List ; list.RemoveAt(2); list[1] = 4;
But of course if you don’t know if the numbers you wish to remove exist or not, and where they exist, you obviously need to search for them.
Now, lets say you know that the list is sorted, and is huge. Let us consider the case where the list has 10,000 elements random sorted numbers, and you wish to remove all numbers that are in list toRemove , which is also sorted
THEN you can actually iterate the list once except for toRemove.Count times, like so:
And if the list might contain duplicate numbers and you want to remove 4 in a way that not a single 4 will exist, then you need to do:
int j = 0; for (int i = 0; i < list.Count && j < toRemove.Count; i++) < var currRemove = toRemove[j]; while (list[i] == currRemove) < list.RemoveAt(i); i--; >j++; >
If you want it to be more clean and less efficient, you can do:
list = list.Except(toRemove).Union(toAdd).ToList();
and if you don’t want to add items that already exist:
var tmp = list.Except(toRemove); list = list.Union(toAdd.Except(tmp)).ToList();
But I must say this would be terribly slow and you might want to reconsider using a list, and perhaps using a HashTable or a Dictionary .
Adding multiple elements to a list in one line C#, To make the code cleaner you could pass lists around. Then add the list with the .AddRange method, see .net 4.7 manual. Toppings.AddRange(); public Pizza(ECrust crust, EPizzaSize size, List
Split List into Multiple Lists by Criteria c#
List data = new List(); List ages = new List(); List result = data.Where(p => ages.Contains(p.Age)).ToList();
List personAgeList = PersonList.Where(p => AgeList.Contains(p.Age)).ToList();
This is some quick code for you, without LINQ. First you create new list of type Person , then loop over your Person list, and for every person you check if age is the same as one in your age list.
List finalList=new List(); foreach (var a in PersonList) < foreach (var b in AgeList) < if (a.Age==b) < finalList.Add(a); break; >> >
How to merge 2 List and removing duplicate values, I have two lists List that I need to combine in third list and remove duplicate values from that lists. A bit hard to explain, so let me show an example of what the code looks like and what I want as a result, in sample I use int type not ResultAnalysisFileSql class. first_list = [1, 12, 12, 5]
How to add to a List while using Multi-Threading?
If you need to access a collection from multiple threads, you should either use synchronization, or use a SynchronizedCollection if your .NET version is 3.0 or higher.
Here is one way to make the collection accessible to your thread:
SynchronizedCollection reports = new SynchronizedCollection(); foreach (form in forms) < var reportThread = new Thread(() =>ParseForm(form, reports)); reportThread.Start(); > void ParseForm(Form form, SynchronizedCollection reports)
If you are on .NET 4 or later, a much better alternative to managing your threads manually is presented by various classes of the System.Threading.Tasks namespace. Consider exploring this alternative before deciding on your threading implementation.
In before we realized it was .Net 3.5, keep for reference on .Net 4
If you don’t need any order within the list, an easy «fix» is to use the ConcurrentBag class instead of a list. If you need more order, there is also a ConcurrentQueue collection too.
If you really need something more custom, you can implement your own blocking collection using BlockingCollection. Here’s a good article on the topic.
You can also use Parallel.Foreach to avoid the explicit thread creation too:
private void ParseForms() < var reports = new ConcurrentBag(); Parallel.ForEach(forms, (form) => < reports.Add(ParseForm(form)); >); > private byte[] ParseForm(form)
Why is enumerate files returning the same file more than once?
Check that out. It shows I think exactly what you want to do.
It creates a list on the main thread then adds to it from a different thread. your going to need
using System.Threading.Tasks
Files.Clear(); //List Task.Factory.StartNew( () => < this.BeginInvoke( new Action(() =>< Files.Add("Hi"); >)); >);
C# Accessing a list from multiple methods, I am looking to access a list from different methods in the same class.Is there an easier way to access the movieTitle list without making a new list for each method? Do I have to make a reference to the list in every method? or should I put them all into a separate class all together? My overall goal is to have …
Csharp c initialize list of lists
This keeps the internal array to a known size and prevents internal array re-sizing as you add the known number of elements. I thought that lists used arrays internally.
List array initialization c#
List aif = new List(); for (int i = 0; i < 5; i++) < aif.Add(null); >aif[0] = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844); aif[1] = new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972); aif[2] = new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844); aif[3] = new authorinfo("Robinson Crusoe", "Daniel", "Defoe", 1719); aif[4] = new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968); //authorinfo ai = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844); foreach (authorinfo i in aif)
Okay the thing is, when i remove the for-loop at the top the program wont start, why? Because i need to add null to the list.
I know I’m doing this the wrong way. I just want the aif2 to be there, it doesn’t make sense that i have to add null objects to not get an outof range error .
Just add the new object instances themselves:
List aif = new List(); aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844)); //. and so on
Right now you are using null as a placeholder element which you then overwrite using the indexer — you don’t have to do this (nor should you).
As an alternative and if you know your list element s in advance you could also use the collection initializer:
When you access a list element via index like so,
you’re assuming that the collection foo has at least five (0,1,2,3,4) elements. You’re getting an out of range error because, without the for loop, you’re trying to access an element that hasn’t been allocated.
There are a couple of ways to handle this. The most obvious is to use List<>.Add() :
List aif = new List(); aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844)); aif.Add(new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972); // .
For a toy (homework) problem like this, though, you could just initialize the list at construction:
One of the most useful things about List<> and other collections is that they’re dynamically sized , as opposed to an array. Think of a List<> as a linked list that handles all of the node connections for you. Like a linked list, a List<> doesn’t have nodes until you add them, which your for loop is doing. In an array, space for references to all elements is allocated up front, so you can immediately access them, but you can’t dynamically modify the size of an array.
How to initialize a List to a given size (as opposed to capacity)?, One could quite convincingly argue that lists are the «next generation» arrays, adding flexibility with almost no penalty. Therefore one should use them by
Inline Initializing C# Lists
C# includes a method for initializing Lists that means you do not need to be sequentially Duration: 1:25
Creating a List of given size, all initialized to some value, in C#
Is there a compact manner in which the following can be done?
List a = new List(); for (int i = 0; i < n; ++i) a.Add(0);
i.e., creating a list of n elements, all of value 0.
Enumberable.Repeat would be the shortest method I can think of:
var a = Enumerable.Repeat(0, n).ToList();
You can use the Enumerable.Repeat generator:
var list = new List(Enumerable.Repeat(0, n));
List x = Enumerable.Repeat(value, count).ToList();
C# List of Lists capacities, @MichaelPetito Regardless of the initialized capacities, the List
C# Lists: initialize with size, why then can't use [] access until after .Add()?
This works fine with an array:
int[] a = new int[10]; for (int i = 0; i
But this throws an ArgumentOutOfRangeException with a list:
List a = new List(10); for (int i = 0; i
Why is that? I thought that lists used arrays internally.
You are initializing the capacity, not the size. The count will still be zero. Initializing the capacity allows an optimization to size the internal data structure (an array) when you know the maximum size when creating the list. This keeps the internal array to a known size and prevents internal array re-sizing as you add the known number of elements.
new List(10) creates a new list with the initial capacity of 10 items. The list is still empty.
You need to add items to it before you can access them by index.
When you don't specify a capacity, your collection will be reallocated several times if it even grows to have 100 elements. This makes populating your list twice as slow.
C# - Instantiating a List, The syntax int[] array = <1,2,3>;. is special syntactic sugar for array initialization. <1,2,3>is not itself an array yet. This line1,2,3>
Using And Looping Over a List of Lists – C#
You might be familiar with how to loop over a list, but what about a list of lists? You may not even be sure how to create one. This post will cover very simply how to create, use, and loop over a list of lists. This was something I used to create the Undo function in my game Puzzledorf, as I wanted to store what position every object on a grid was for every turn of the game.
If you are new to arrays, though, you might want to look at my overview on arrays first.
Create A List of Lists
To create the List of Lists, you do it like so:
itemBag is our list of lists. In this case, we will be using lists of strings to create a character inventory from an RPG game.
Populating The List of Lists
This is how we add items to our list of lists. First create a temporary list, then add things to it, finally add that to our itemBag:
List weapons = new List(); weapons.Add("Sword"); weapons.Add("Dagger"); weapons.Add("Crossbow"); itemBag.Add(weapons); List potions = new List(); potions.Add("Health Potion"); potions.Add("Strength Potion"); potions.Add("Luck Potion"); itemBag.Add(potions);
Looping Over A List of Lists
Now we can loop over our list of lists:
If you have never looped over an array before, it’s all covered in my overview on arrays.
We need two loops, an outer loop to find each pocket where we store the different items in our itemBag, and then an inner loop to go over each item for each pocket.
Test and run. If you are using Unity, replace Console.WriteLine with Debug.Log.
Sword
Dagger
Crossbow
Health Potion
Strength Potion
Luck Potion
You will notice that our double loop found the weapons pocket first, and displayed all the weapons in that pocket, and then it found the potions pocket, and went over all of the potions in that pocket.
And that’s it – that’s how you loop over a list of lists. Full code below.
Join the Discord. Talk about Game Dev. Talk about Gaming.
List> itemBag = new List>(); List weapons = new List(); weapons.Add("Sword"); weapons.Add("Dagger"); weapons.Add("Crossbow"); itemBag.Add(weapons); List potions = new List(); potions.Add("Health Potion"); potions.Add("Strength Potion"); potions.Add("Luck Potion"); itemBag.Add(potions); for (int a = 0; a < itemBag.Count; a++) < for (int b = 0; b < itemBag[a].Count; b++) < Console.WriteLine(itemBag[a][b]); >> Console.ReadKey();