This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 5 years ago.
I want to define a function with two outputs. The first one is a boolean variable and the second one is 2D array with unknown numbers of rows and columns but the array will be defined if the boolean variable is true and if the boolean variable is false, the array is not defined. how can I define this function? I am thankful if anybody can exemplify it in an example.
Thanks
You want something like this .
Tuple<string, int> NameAndId()
{
// This method returns multiple values.
return new Tuple<string, int>("Test", 100);
}
Why not return null if array is not defined?
public static bool MyMethod(out int[,] array) {
array = null;
...
}
....
int[,] data;
if (MyMethod(out data)) {
....
}
Or in case of C# 7.0+
if (MyMethod(out var data)) {
....
}
Edit: if you want to return an array, but you don't know its Length (or want to adjust it) you can try working with List<T> and put .ToArray() in the end:
using System.Linq;
...
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(10);
...
list.Remove(5);
...
list.RemoveAt(0);
...
array = list.ToArray();
Related
This question already has answers here:
System.Int32[] displaying instead of Array elements [duplicate]
(4 answers)
Closed 2 years ago.
When I make a function to return an array with the correct results.
Instead of giving me the correct results, I get as result System.Int32[].
Anyone an idea why this is?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MultiplyByLength(new int[] {2,3,1,0}));
}
public static int[] MultiplyByLength(int[] arr)
{
return arr.Select(x => x * arr.Length).ToArray();
}
}
You need to format it some how. An array doesn't have a ToString() override that knows how you want to format your type (int[]) to a string, in such cases it just returns the type name (which is what you are seeing)
foreach(var item in MultiplyByLength(new int[] {2,3,1,0})
Console.WriteLine(item);
or
Console.WriteLine(string.Join(Environment.NewLine, MultiplyByLength(new int[] {2,3,1,0}));
or
Console.WriteLine(string.Join(",", MultiplyByLength(new int[] {2,3,1,0}));
I'm trying to get a distinct list to my view.I need to select records from a list randomly and put it in to another list.The following code works..But it contain duplication records..How can I overcome this problem?
Note: the variable "budget" is a parameter passed in to the controller and "model1" is a List of PlanObjectsViewModel
int count = 0;
foreach (var item in model1) { count++; }
List<PlanObjectsViewModel> result = new List<PlanObjectsViewModel>();
Random rand = new Random();
double? temp=0;
while(budget>temp)
{
int randi = rand.Next(0, count);
var nthItem = model1.OrderBy(p => p.Id).Skip(randi).First();
temp += nthItem.Price;
if (!result.Contains(nthItem)) // Think this is the wrong point
{
result.Add(nthItem);
}
}
Use a HashSet<PlanObjectsViewModel>
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Input array that contains three duplicate strings.
string[] array1 = { "cat", "dog", "cat", "leopard", "tiger", "cat" };
// Display the array.
Console.WriteLine(string.Join(",", array1));
// Use HashSet constructor to ensure unique strings.
var hash = new HashSet<string>(array1);
// Convert to array of strings again.
string[] array2 = hash.ToArray();
// Display the resulting array.
Console.WriteLine(string.Join(",", array2));
}
}
Output:
cat,dog,cat,leopard,tiger,cat
cat,dog,leopard,tiger
there are two ways to do this, use a hashset instead of list for your result, or use Distinct()
HashSet<PlanObjectsViewModel> result
or
return result.Distinct();
You will have have to implement the Equals() method for this to work with objects, a which point your current code should work too.
Actually you have made it the correct way. For me it looks like you didnt implemented Equals and GetHashCode which are used by List.Contains to compare objects. Well basically GetHashCode is not mandatory but its a good design if you implemented the one to implement the other one.
But ofcourse you can use HashSet as pointed in the other answeres.
This question already has answers here:
How to initialize a List<T> to a given size (as opposed to capacity)?
(16 answers)
Initialize a List<int> with LINQ query
(6 answers)
Closed 8 years ago.
let's say I have a simple List<bool>. I want to initialize it and add e.g 100 elements to it. To do so, I can do:
var myList = new List<bool>();
for (int i = 0; i < 100; i++)
{
myList.Add(false);
}
but it's not the most elegant approach. Is there any built-in method to simplify it ? I don't want any loops, just for curiosity
Using Enumerable.Repeat
var myList = Enumerable.Repeat(false, 100).ToList();
which
Generates a sequence that contains one repeated value.
false is easy, since it's the default value of boolean:
new List<bool>(new bool[100]);
You could use LINQ and more specifically the Select and ToList extension methods:
var myList = Enumerable.Range(1, 100).Select(x => false).ToList();
List<T> has no specific method to do this. The loop is your best option.
However, you can make it more efficient at runtime, by initializing the list with an initial capacity:
var myList = new List<bool>(100);
When using this constructor, the list will internally allocate an array of 100 elements. If you use the default constructor, it will start of with first 0 and then 4 elements. After 4 items have been added, the list will allocate an array of 8 elements and copy the 4 that were already added over. Then it will grow to 16, 32, 64 and finally 128. All these allocations and copy operations can be avoided by using the constructor with the initial capacity.
Alternatively, if you need to do this in different places in your program, you could make an extension method:
public static void Initialize<T>(this List<T> list, T value, int count)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (list.Count != 0)
{
throw new InvalidOperationException("list already initialized");
}
if (list.Capacity < count)
{
list.Capacity = count;
}
for (int i = 0, i < count, i++)
{
list.Add(value);
}
}
You would use it like this:
var myList = new List<bool>();
myList.Initialize(false, 100);
The other option that you have is to use an array.
var myList = new bool[100];
The interesting thing about this specific example is that you do not have to initialize the array. Since false is the default value for bool, all elements in the array will automatically have the value false. If your list does not need to resize dynamically, this is certainly an option to consider.
You can use List.AddRange:
List<bool> list = new List<bool>();
list.AddRange(Enumerable.Repeat(default(bool), 100));
This question already has answers here:
Adding values to a C# array
(26 answers)
Closed 9 years ago.
How can i create a int array in class.
And i have to add values to that array.
Not to a specific key.
i declared array as
public int[] iArray;
from function i have to insert values of i to array. My i values gets change. So i have to save those in a array.
iArray[] = i;
But it shows error.
Handling arrays is pretty straight forward, just declare them like this:
int[] values = new int[10];
values[i] = 123;
However, arrays in C# have fixed size. If you want to be able to have a resizeable collection, you should use a List<T> instead of an array.
var values = new List<int>();
values.Add(123);
Or as a class property:
class SomeClass
{
private List<int> values = new List<int>();
public List<int> Values { get { return this.values; } }
}
var someInstance = new SomeClass();
someInstance.Values.Add(123);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Remove element of a regular array
I have a method defined which returns class array.
ex: Sampleclass[]
The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.
for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{
**// How to remove ??**
}
}
Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:
var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
.ToArray();
It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following
var i = 0;
while (i < Sampleclass.Count) {
if (Sampleclass[i].Address.Contains("")) {
Sampleclass.RemoveAt(i);
} else {
i++;
}
}