Get the value of array using c# [duplicate] - c#

This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 7 years ago.
I got an array
string [] strings = new string[] {"1", "2", "2", "2", "1"};
You can see the value of the array is just 1 and 2, just 2 values, you could say, and I want to get those value out...What I did is here, just a start:
string[] strings = new[] { "1", "2", "2", "2", "1"};
int[] ints = strings.Select(x => int.Parse(x)).ToArray();
I don't what is next...Anyone helps?

You mean you just want an array int[] {1, 2}?
string[] strings = new[] { "1", "2", "2", "2", "1"};
int[] ints = strings.Select(int.Parse).Distinct().ToArray();

You may simply add a distinct to get the unique values:
int[] ints = strings.Select(x => int.Parse(x)).Distinct().ToArray();
Thus your array contains the elements {1, 2}

Classic way:
string[] strings = new[] { "1", "2", "2", "2", "1" };
List<int> items = new List<int>();
for (int i = 0; i < strings.Length; i++)
{
int item = int.Parse(strings[i]);
if (!items.Contains(item))
items.Add(item);
}

Related

Set subtraction while keeping duplicates

I need to get the set subtraction of two string arrays while considering duplicates.
Ex:
var a = new string[] {"1", "2", "2", "3", "4", "4"};
var b = new string[] {"2", "3"};
(a - b) => expected output => string[] {"1", "2", "4", "4"}
I already tried Enumerable.Except() which returns the unique values after subtract: { "1", "4" } which is not what I'm looking for.
Is there a straightforward way of achieving this without a custom implementation?
You can try GroupBy, and work with groups e.g.
var a = new string[] {"1", "2", "2", "3", "4", "4"};
var b = new string[] {"2", "3"};
...
var subtract = b
.GroupBy(item => item)
.ToDictionary(chunk => chunk.Key, chunk => chunk.Count());
var result = a
.GroupBy(item => item)
.Select(chunk => new {
value = chunk.Key,
count = chunk.Count() - (subtract.TryGetValue(chunk.Key, out var v) ? v : 0)
})
.Where(item => item.count > 0)
.SelectMany(item => Enumerable.Repeat(item.value, item.count));
// Let's have a look at the result
Console.Write(string.Join(", ", result));
Outcome:
1, 2, 4, 4
By leveraging the undersung Enumerable.ToLookup (which allows you to create dictionary-like structure with multi-values per key) you can do this quite efficiently. Here, because key lookups on non-existent keys in an ILookup return empty IGrouping (rather than null or an error), you can avoid a whole bunch of null-checks/TryGet...-boilerplate. Because Enumerable.Take with a negative value is equivalent to Enumerable.Take(0), we don't have to check our arithmetic either.
var aLookup = a.ToLookup(x => x);
var bLookup = b.ToLookup(x => x);
var filtered = aLookup
.SelectMany(aItem => aItem.Take(aItem.Count() - bLookup[aItem.Key].Count()));
Try the following:
var a = new string[] { "1", "2", "2", "3", "4", "4" }.ToList();
var b = new string[] { "2", "3" };
foreach (var element in b)
{
a.Remove(element);
}
Has been tested.

How to convert string[] to int in C# [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 8 years ago.
Improve this question
I'm a begginer to C# programmer and I have a problem in my code with one string.
I want to know how I can convert this string:
x = {"1","2","0",",","1","2","1",",","1","2","2"}
into something like this:
x = {"120","121","122"}
The variable x is assigned as string and I want it assigned as int. The purpose of this is to get how many numbers are between lets say 120 and 130, which in my string would be 3.
Many Thanks.
string[] x = { "1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2" };
int[] y = string.Join(string.Empty, x)
.Split(',')
.Select(s => int.Parse(s))
.ToArray();
I think you can do this in three lines as follows:
var x = new []{"1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2"};
var fullString = String.Join("", x, 0, x.Length);
// get as a string array:
// x = fullString.Split(new[] {','});
// get as an integer array:
var intArray = (fullString.Split(new[] {','}))
.Select(_ => Int32.Parse(_)).ToArray();
In steps this is (1) create the string, (2) join the string, (3) split the string on the separator (which appears to be the comma in your case).
Best of luck!
Not sure why you want to do this but never the less it can be achieved quite simply using LINQ to Objects basic String methods.
var x = new string[] { "1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2" };
var y = String.Join(String.Empty, x).Split(',');
foreach (var s in y)
Console.WriteLine(s);
Update 23/05/2014
As per the comments, here is some code that will do what you want (i.e. count the numbers between the range 120-130 inclusive).
var min = 120;
var max = 130;
var count = y
.Select(o => Int32.Parse(o))
.Count(o => (min <= o) && (o <= max));
Console.WriteLine(count);
You should first add the 3 strings together to get the correct "120","121","122" as a string
Then you could use a forloop or something equivalent to do val.toint();
EDIT:
Changing a list from list String to Int and keeping the same variable seems abit unnecessary to me
string[] x = { "1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2" };
StringBuilder sb = new StringBuilder();
foreach (var item in x)
{
sb.Append(item);
}
string str = sb.ToString();
string[] myArr = str.Split(',');
int[] numArr = new int[myArr.Length];
for (int i = 0; i < myArr.Length; i++)
{
numArr[i] = int.Parse(myArr[i]);
}
with a bit of effort, youll be able to find this,(you are not supposed to just post a question, next time do some research please) but whilst the question is here any way:
string[] items;
items = new string[5];
int[] intitems;
intitems = new int[5];
foreach (string item in items)
{
int i = 0;
int.TryParse(items[i], out intitems[i]);
}
an easy and understandable way of doing it. the loop pretty much explains it self
Here is an approach using several string methods and LINQ:
string[] x = { "1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2" };
string all = string.Join("", x); // "120,121,122"
string[] parts = all.Split(','); // { "120", "121", "122" }
int i = int.MinValue; // variable which is used in below query
int[] y = parts // LINQ query
.Where(s => int.TryParse(s.Trim(), out i)) // filters out invalid strings
.Select(s => i) // selects the parsed ints
.ToArray(); // creates the final array

Insert Values from string[] arrays to an ArrayList of records

I will add the values in the String[] in to the Arraylist. But, I want to access those string values from the ArrayList.
I tried this way.
private void Form1_Load()
{
fr = new string[5] { "1", "2", "3", "4", "5" };
bd = new string[5] {"a", "b","c", "d", "e"};
m = new ArrayList();
dosomething();
}
private void dosomething()
{
string[] record = new string[3];
for (int i = 0; i < 5; i++)
{
record[0] = "1";
record[1] = fr[i];
record[2] = bd[i];
m.Add(record);
}
}
I don't want to use the for loop is that any other way to do this???
I recommend you to use dictionaries. It is in my opinion the quickest way to store / access data. Also, with arraylists, at runtime, it performs a dynamic transtyping, which makes you loose so much time.
You maybe want to use :
fr = new string[5] { "1", "2", "3", "4", "5" };
bd = new string[5] { "a", "b", "c", "d", "e" };
m = new ArrayList();
fr.ToList().ForEach(_item => m.Add(new String[]{ "1", _item,bd[fr.ToList().IndexOf(_item)]}));
But I would prefere a solution like Fares already recommented...Use A Dictionary
Dictionary - MSDN
Not sure why you need an ArrayList. A generic list might be more suitable for you.
var fr = new string[5] { "1", "2", "3", "4", "5" };
var bd = new string[5] {"a", "b","c", "d", "e"};
int i = 1;
var results = fr.Zip<string, string, string[]>(bd, (a,b) => {
var v = new string [3] { i.ToString(), a,b };
i++;
return v;
}).ToList();

Getting the first element in a string array which is inside a arraylist. C# ASP.net

In one of my web application page, I have a C# code as follows. How do I get the first element in the string array inside the arraylist?
Code
protected void Button3_Click(object sender, EventArgs e)
{
//Array test[9] = new Array();
ArrayList list = new ArrayList();
list.Add(new string[] { "1", "Test1", "20", "30" });
list.Add(new string[] { "2", "Test2", "5", "30" });
list.Add(new string[] { "3", "Test3", "10", "30" });
list.Add(new string[] { "4", "Test4", "20", "30" });
list.Add(new string[] { "5", "Test5", "0", "30" });
list.Add(new string[] { "6", "Test6", "15", "30" });
list.Add(new string[] { "7", "Test7", "10", "30" });
list.Add(new string[] { "8", "Test8", "20", "30" });
list.Add(new string[] { "9", "Test9", "30", "30" });
LabelMessages.Text = "Number of Items: " + list.Count + " Item 1 record 1: " + list[1];
}
Expected Output
Number of Items: 9 Item 1 record 1: 1
Current Output (which is not what I want)
Number of Items: 9 Item 1 record 1: System.String[]
So, suppose that the following code:
list.Add(new string[] { "1", "Test1", "20", "30" });
is change to:
list.Add(new string[] { "Test1", "20", "30" });
then the expected output should be:
Number of Items: 9 Item 1 record 1: Test1
You need the first element of string array and each element of list present a string array so you have to type cast the list element to string array and later access the first element of array. This ((string[])list[0])[0] will give you first element of array at zero locaation of list.
You are using ArrayList which is not generic list, you may use List which is generic list and you will be free from type casting.
LabelMessages.Text = "Number of Items: " + list.Count +
" Item 1 record 1: " +( (string[])list[0])[0];
the expression list[1] will return a type of Object which currently is a string array.
Since it is an Object, you will not be able to directly index it like list[1][1] . you have to explicitly convert it into string array before you can index it.
((string[])list[1])[1];
You can use it like this
LabelMessages.Text = "Number of Items: " + list.Count + " Item 1 record 1: " + ((string[])list[1])[1];
Hi you can acheive reverse parsing you can get the element.
((string[])list[0])[0]

Initializing multidimensional arrays in c# (with other arrays)

In C#, it's possible to initialize a multidimensional array using constants like so:
Object[,] twodArray = new Object[,] { {"00", "01", "02"},
{"10", "11", "12"},
{"20", "21", "22"} };
I personally think initializing an array with hard coded constants is kind of useless for anything other than test exercises. Anyways, what I desperately need to do is initialize a new multidimensional array as above using existing arrays. (Which have the same item count, but contents are of course only defined at runtime).
A sample of what I would like to do is.
Object[] first = new Object[] {"00", "01", "02"};
Object[] second = new Object[] {"10", "11", "12"};
Object[] third = new Object[] {"20", "21", "22"};
Object[,] twodArray = new Object[,] { first, second, third };
Unfortunately, this doesn't compile as valid code. Funny enough, when I tried
Object[,] twodArray = new Object[,] { {first}, {second}, {third} };
The code did compile and run, however the result was not as desired - a 3 by 3 array of Objects, what came out was a 3 by 1 array of arrays, each of which had 3 elements. When that happens, I can't access my array using:
Object val = twodArray[3,3];
I have to go:
Object val = twodArray[3,1][3];
Which obviously isn't the desired result.
So, is there any way to initialize this new 2D array from multiple existing arrays without resorting to iteration?
This would work if you switched to jagged arrays:
int[] arr1 = new[] { 1, 2, 3 };
int[] arr2 = new[] { 4, 5, 6 };
int[] arr3 = new[] { 7, 8, 9 };
int[][] jagged = new[] { arr1, arr2, arr3 };
int six = jagged[1][2];
Edit To clarify for people finding this thread in the future
The code sample above is also inadequate as it results in an array of arrays (object[object[]]) rather than a jagged array (object[][]) which are conceptually the same thing but distinct types.
You are trying to assign array references to an array. For more details please read - Jagged Arrays.
Try this,
Object[] first = new Object[] { "00", "01", "02" };
Object[] second = new Object[] { "10", "11", "12" };
Object[] third = new Object[] { "20", "21", "22" };
Object[][] result = { first, second, third };
foreach (object [] ar in result)
{
foreach (object ele in ar)
{
Console.Write(" " + ele);
}
Console.WriteLine();
}
I'm struggling to fully understand what you're really trying to achieve. If I got it right, you have some "lists" of strings, which you need to store in another list.
First of all, I'd recommend you to use a more modern approach than arrays. C# offers you IEnumerable<> and IList<> interfaces and all the stuff that derives from them, so no need to stick with old fashioned arrays.
You could do something like this:
var list1 = new List<string> { "foo1", "foo2", "foo3" };
var list2 = new List<string> { "foo4", "foo5", "foo6" };
var list3 = new List<string> { "foo7", "foo8", "foo9" };
var listOfStrings = new List<List<string>> { list1, list2, list3 };
Then if you want to access "foo6" you write:
var temp = listOfStrings[1][2];
The following works just fine:
var a = new object[] { 0, 1, 1, 2 };
var b = new object[] { "0", "5", "0", "0" };
var c = new object[] { true, true, true, false };
object[][] m = new object[][] { a, b, c };
var two = m[0][3];
var bar = m[1][1];
var f = m[2][3];

Categories