Insert string value to object array - c#

I have below array of type object
object[] myarray = new object[] { "1", "Success"};
I want to insert string value at first position in myarray is there any method
to do this result should be like below:
I want array like below
object[] myarray = new object[] { "logFile","1", "Success"};

If you need to stick with the array:
myarray = new object[]{"logFile"}.Concat(myarray).ToArray();
The classic, non-LINQ (and most efficient) way is to use Array.Copy:
var newArray = new object[myarray.Length + 1];
newArray[0] = "logFile";
Array.Copy(myarray, 0, newArray, 1, myarray.Length);
// myarray = newArray;

You can switch to List<string> which can grow dynamically
List<string> myArray= new List<string> { "1", "Success"};
and use List.Insert
myArray.Insert(0,"LogFile");
From MSDN how List.Insert works
If Count already equals Capacity, the capacity of the List is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.
If index is equal to Count, item is added to the end of List.

Related

Make an array completely empty

I want to make this array completely empty.
string[] strNumbers = new string[3] { "1", "2", "3" };
So I want it to be this
strNumbers = {}
Using the function
Array.Clear();
why don't use this
strNumbers = new string[3] ;
Array.Clear will set elements of array to the default values (null for string) but will keep the size of array. Just new up the array:
strNumbers = new string[0];
Or even better:
strNumbers = Array.Empty<string>();
Unclear what you are asking.
Create a new array with no elements
string[] strNumbers = new string[0];
or
string[] strNumbers = Array.Empty<string>();
strNumbers.Length will be zero
Create a new array but leave contents empty
string[] strNumbers = new string[3];
contents will be three null values
Take an existing array and remove all the elements
Arrays in C# are of fixed size. You cannot add or remove elements from arrays. If you need variable size arrays, use List<string> or some other collection type.
Take an existing array and set the contents to their default values
for(int i=0; i<strNumbers.Length; i++)
{
strNumbers[i] = default(string);
}
or
Array.Clear(strNumbers, 0, strNumbers.Length);

How can I return array elements specified in one line using an array of indexes?

Is there a way for me to say I want some specific values from an array, possibly used in a way such as this?
string[] values = new string[]{"boogie","woogie","all","night"};
string[] refinedValues = values.GetIndexes(new int[]{ 0, 2 });
In this situation, refinedValues would be an array containing the values "boogie" and "all".
You can do this
var refinedValues = new[] { 0, 2 }.Select(values.ElementAt);
A custom extension method would look like this
public static class EnumerableExtensions {
public static IEnumerable<T> GetValues<T>(this IEnumerable<T> enumerable, params Int32[] indices) {
return indices.Select(enumerable.ElementAt);
}
}
Yes, use a bit of LINQ:
string[] values = new string[] { "boogie", "woogie", "all", "night" };
var indexes = new[] {0, 2};
string[] refinedValues = values.Where((e, i) => indexes.Contains(i)).ToArray();
//refined-values contains "boogie", "all"

passing normal items and array items to params function C#

i want to add new row to table but by passing both normal variables and array variable like the example below
int value1=1;
int value2=2;
int[] numbers = new int[] {3, 4, 5};
DataTable1.Rows.Add(value1,value2,numbers) // numbers as single items so the row will contain 5 values (1,2,3,4,5)
so should i build a new array and pass it ? or there a code spell to do that ?
thanks
This helper method will create a list from 1 to 5:
public IEnumerable<T> GetItemsAndCollectionsAsItems<T>(params object[] itemsAndCollections)
{
var result = new List<T>();
foreach (var itemOrCollection in itemsAndCollections)
{
var collection = itemOrCollection as IEnumerable<T>;
if (collection == null)
{
result.Add((T)itemOrCollection);
}
else
{
result.AddRange(collection);
}
}
return result;
}
And you call it this way:
int value1 = 1;
int value2 = 2;
int[] numbers = new int[] { 3, 4, 5 };
// Returns 1,2,3,4,5
IEnumerable<int> values = GetItemsAndCollectionsAsItems<int>(value1, value2, numbers);
Not sure to be happen with this Int Array but yah, have a look on this link, which stores data same as you want. Simply some tricky things have to do.

Identify where I am in an array

I have a string array in C# like so:
string[] sites = new string[] {
"http://foobar.com",
"http://asdaff.com",
"http://etc.com"
};
I'm using this array in a foreach and I would like to be able to add a "type" value of 1, 2, or 3, depending on which site I am currently iterating through. I am concatenating data with the StringBuilder from these sites. Now, I could store the site as a varchar, but it would be really neat, since this array will NEVER change to associate a number with the string and build it that way.
Use for loop instead of foreach:
for(int i = 0; i < sites.Length; i++)
{
// use sites[i]
}
LINQ's Select can be used to project an index onto a collection.
sites.Select((x, n) => new { Site = x, Index = n })
You can use a dictionary for this - Dictionary<int, string> (or Dictionary<string, int>).
var sitesWithId = new Dictionary<string, int>
{
new { "http://foobar.com", 1},
new { "http://asdaff.com", 2},
new { "http://etc.com", 3}
}
Another option is to just use a List<string> and IndexOf to find out the index.
var sites = new List<string> {
"http://foobar.com",
"http://asdaff.com",
"http://etc.com"
};
var foobarIndex = sites.IndexOf("http://foobar.com");
A third option, using the static IndexOf methods of Array and not changing your array at all:
var foobarIndex = Array.IndexOf(sites, "http://foobar.com");
Try with for loop;
for(int i = 0; i < sites.Length; i++)
{
Console.WriteLine(sites[i]);
}
using for elements of sites[] array like this;
sites[1]
sites[2]
sites[3]
or you can use Dictionary<TKey, TValue> as Oded suggest.

How to create multidimensional array in C#?

I have a dictionary from which I like to create a multidimensional array through c#.
foreach (KeyValuePair<string, int> pair in rptdata)
{
string s2 = pair.Key;
int s1 = pair.Value;
// var ccdata1 = new[] { new object[] { "Item1", 1 } };
// object value = cdata1[s1,s1];
}
I need to add code inside the foreach look so that it can create something like the following:
var ccdata = new[] { new object[] { "Item1", 1 }, new object[] { "Item2", 2 } };
Note that Item1,Item2 would come from str1 and 1,2 would come from int1.
I am not sure how to iterate though to populate the multidimensional object array.
You could do it in one query like this. Linq is pretty great at transforming data. If you want to turn it into JSON afterwards you can use a library, something like Json.NET.
var ccdata = rptdata
.Select( i => new object[]{ i.Key, i.Value } )
.ToArray();

Categories

Resources