How can ı remove from duplicated items in C#? - c#

I have a list in the below it has 18 value.I have another list(include unique 6 value) created by random numbers(1,18), and they are unique.
When i do these for example elidenkiKartlar list shows me 6 unique values, but i have 2 list more in other lists, I have same values for example in elindekiKartlar=K1,K3,S4,RD-1,S2,M4 in another list K1,K4,RD-2,S4,K3, i have same values (K1,K3) e.g.
How can i remove them ? How can I share this big list to 3 equal(6,6,6) part ?
Thanks for your advise from now..
public List<string> kartlar = new List<string>
{
"S1",
"S2",
"S3",
"S4",
"S5",
"M1",
"M2",
"M3",
"M4",
"M5",
"K1",
"K2",
"K3",
"K4",
"K5",
"RD-1",
"RD-2",
"RD-3",
};
//Creating uniqe random list
int [] sayilar=new int[6];
for (int i = 0; i < sayilar.Length; i++)
{
essiz:
sayilar[i] = random.Next(0, 18);
for (int j = 0; j < i; j++)
{
if (sayilar[i]==sayilar[j])
{
goto essiz;
}
}
}
//Adding string items by randomList index
foreach (var sayi in sayilar)
{
elindekiKartlar.Add(kartlar[sayi]);
}

Use Distinct Method
var uniqueValues = kartlar.Distinct().ToList();

Try this
elindekiKartlar.Distinct();

Related

print Section name and it's own employees with their ages using jagged arrays

I am trying to use jagged arrays in order to print sections' names with their names of employees and ages
I tried like this:
string[] sections= new string[50];
sections[0] = "It";
sections[1] = "Hr";
string[][,] employeeTree = new string[6][,];
employeeTree [0] = new string[,] { {"mark","20"},{ "mike", "30" },{ "michel", "3" },{ "joerge", "40" }};
My problem is iterating the employees arrays to print them ,
how can I do it? and if there were examples it will be more better
You have a 2-D Array structure for employeeTree.
So the straightforward way would be to iterate twice on the 2-D array to access the elements.
The simplest way is like below :
foreach(var emp in employeeTree.Where(x => x != null) )
foreach(var object1 in emp)
Console.WriteLine(object1.ToString());
This will print the below output:
mark
20
mike
30
michel
3
joerge
40
You can do formatting on this to print them in a single line like below :
foreach (var emp in employeeTree.Where(x => x != null))
for (int i = 0; i < emp.GetLength(0); i++)
{
Console.WriteLine(emp[i,0] + emp[i,1]);
}
foreach(string[,] employee in employeeTree.Where(x => x != null)) {
int max = employee.GetLength(0);
for (int i = 0; i < max; i++) {
Console.WriteLine($"{employee[i, 0]}, {employee[i, 1]}");
}
}

Using "foreach" in string array c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Good Morning,
I need a foreach loop to print the sequence below line by line:
loop1 a0,a1,a2
loop2 b0,b1,b2
loop3 c0,c1,c2
This is my first post, so sorry for any lack of information.
private void button1_Click(object sender, EventArgs e)
{
int col0_int = 0;
var col0_elements = new string[] { "a0", "b0", "c0", "d0", "e0", "f0", "g0", "h0", };
IList<string> col0_all = col0_elements;
String[] col0_list = new String[col0_all.Count];
List<string> col0_each = new List<string>();
foreach (string element in col0_elements)
{
col0_list[col0_int++] = element;
col0_each.Add(element);
}
int col1_int = 0;
var col1_elements = new string[] { "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", };
IList<string> col1_all = col1_elements;
String[] col1_list = new String[col1_all.Count];
List<string> col1_each = new List<string>();
foreach (string element in col1_elements)
{
col1_list[col1_int++] = element;
col1_each.Add(element);
}
int col2_int = 0;
var col2_elements = new string[] { "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", };
IList<string> col2_all = col2_elements;
String[] col2_list = new String[col2_all.Count];
List<string> col2_each = new List<string>();
foreach (string element in col2_elements)
{
col2_list[col2_int++] = element;
col2_each.Add(element);
}
//LOOP script here
}
Assuming all arrays are equal length:
for (int i = 0; i < col0_list.Length; i++)
{
Console.WriteLine($"{col0_all[i]},{col1_all[i]},{col2_all[i]}");
}
If you can ensure that your three lists always contain the required elements at the correct position, a fast solution would be to use the LINQ Enumerable.Zip extension method two times:
var results = col0_elements.Zip(col1_elements, (x, y) => $"{x}, {y}")
.Zip(col2_elements, (x, y) => $"{x}, {y}");
This produces an IEnumerable<string> (over which you can loop) with the following content:
{
"a0, a1, a2",
"b0, b1, b2",
"c0, c1, c2",
"d0, d1, d2",
"e0, e1, e2",
"f0, f1, f2",
"g0, g1, g2",
"h0, h1, h2"
}
You are overcomplicating the things.
For each string array you are creating an empty string array and a list with only one element...
With this approach you are esentially creating a string matrix.
var col0_elements = new string[] { "a0", "b0", "c0", "d0", "e0", "f0", "g0", "h0", };
var col1_elements = new string[] { "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", };
var col2_elements = new string[] { "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", };
IList<string[]> all_elements = new List<string[]>{ col0_elements, col1_elements, col2_elements };
for (int i = 0; i < col0_elements.Length; i++) // Row iteration
{
foreach (var cell in all_elements) // Cell iteration
{
Console.Write(cell[i]);
}
Console.WriteLine();
}
You can get those with a for loop:
for (int index = 0; index < col0_each.Count; index++)
{
string col0String = col0_each[index];
string col1String = col1_each[index];
string col2String = col2_each[index];
(print as desired);
}
This code doesn't include any error checking to make sure each list is long enough; it assumes they are all the same length.
There are extra lists in the code that could be simplified, though that's not what you asked about.

Finding differences within 2 Lists of string arrays

I am looking to find the differences between two Lists of string arrays using the index 0 of the array as the primary key.
List<string[]> original = new List<string[]>();
List<string[]> web = new List<string[]>();
//define arrays for List 'original'
string[] original_a1 = new string[3]{"a","2","3"};
string[] original_a2 = new string[3]{"x","2","3"};
string[] original_a3 = new string[3]{"c","2","3"};
//define arrays for List 'web'
string[] web_a1 = new string[3]{"a","2","3"};
string[] web_a2 = new string[3]{"b","2","3"};
string[] web_a3 = new string[3]{"c","2","3"};
//populate Lists
original.Add(original_a1);
original.Add(original_a2);
original.Add(original_a3);
web.Add(web_a1);
web.Add(web_a2);
web.Add(web_a3);
My goal is to find what is in List 'original' but NOT in 'web' by using index 0 as the primary key
This is what I tried.
List<string> differences = new List<string>(); //differences go in here
string tempDiff = ""; // I use this to try and avoid duplicate entries but its not working
for(int i = 0; i < original.Count; i++){
for(int j = 0; j< web.Count; j++){
if(!(original[i][0].Equals(web[j][0]))){
tempDiff = original[i][0];
}
}
differences.Add(tempDiff);
}
OUTPUT:
foreach(string x in differences){
Console.WriteLine("SIZE " + differences.Count);
Console.WriteLine(x);
ConSole.ReadLine();
}
SIZE 3
SIZE 3
x
SIZE 3
x
Why is it reporting the mismatch 3 times instead of once?
Using linq you can just go:
var differences = orignal.Except(web).ToList();
Reference here
This will give you the values that are in original, that don't exist in web
Sorry didn't read your question properly, to answer your question:
You have a nested for-loop. So for each value of original (3) it will loop through all values of web (3), which is 9 loops total.
In 3 cases it doesn't match and therefore outputs 3 times.
I think this is what you want. I use Linq to grab the primary keys, and then I use Except to do original - web. By the way, you can use == instead of Equals with strings in C# because C# does a value comparison as opposed to a reference comparison.
List<string[]> original = new List<string[]>
{
new string[3] { "a", "2", "3" },
new string[3] { "x", "2", "3" },
new string[3] { "c", "2", "3" }
};
List<string[]> web = new List<string[]>
{
new string[3] { "a", "2", "3" },
new string[3] { "b", "2", "3" },
new string[3] { "c", "2", "3" }
};
var originalPrimaryKeys = original.Select(o => o[0]);
var webPrimaryKeys = web.Select(o => o[0]);
List<string> differences = originalPrimaryKeys.Except(webPrimaryKeys).ToList();
Console.WriteLine("The number of differences is {0}", differences.Count);
foreach (string diff in differences)
{
Console.WriteLine(diff);
}
And here it is without Linq:
var differences = new List<string>();
for (int i = 0; i < original.Count; i++)
{
bool found = false;
for (int j = 0; j < web.Count; j++)
{
if (original[i][0] == web[j][0])
{
found = true;
}
}
if (!found)
{
differences.Add(original[i][0]);
}
}
To answer your question: It is a nested for loop as stated in JanR's answer. This approach will make you reiterate to your web count 9 times, thus listing your mismatched key three times.
What could be a better way to do is this:
//Check for originals not introduced in web.
if(original.Count > web.Count)
{
for(int y = web.Count; y < original.Count; y++)
{
differences.Add(original[y][0]);
}
}
//Check if Web has value, if not, everything else is done on the first for loop
if(web.Count > 0)
{
for(int i = 0; i < original.Count; i++)
{
if(!original[i][0].Equals(web[i][0]))
differences.Add(original[i][0]);
}
}
Also, the output is in a for loop, when you just need one result, the length of the mismatch. You can do that without a loop.
Console.WriteLine("SIZE " + differences.Count);
This is, of course to make it kinda simpler if you're not used to using LINQ statements, but if you can do so with LINQ, then by all means, use LINQ as it's more efficient.
You can get the difference by using Except extension method like this:
var originalDic = original.ToDictionary(arr => arr.First());
var webDic = web.ToDictionary(arr => arr.First());
var differences =
originalDic
.Except(webDic, kvp => kvp.Key)
.Select(kvp => kvp.Value)
.ToList();
The trick here is to first convert your original and web lists into a Dictionary using the first element of each array as key and then perform Except.

Invert/Rotate List of list (List<List<int >) having different items in innerlist

I have a List of list. I want to revert this (rows become columns and columns become rows. I am able to invert it if number of elements are same in inner list. But if number of elements in inner list are different I am not able to do so.
So lets say I have this list
1 2 3 4
5 6 7 8
I get this output
1 5
2 6
3 7
4 8
But if I have input like this, then I receive errors
1
2 3 4
5 6 7
Here is the code,
var invertedRows = matrix.Select(row => row.Count).Concat(new[] {0}).Max();
var result = new Point3D[invertedRows][];
for (var i = 0; i < invertedRows; i++)
{
var invertedColumns = matrix[i].Count;
result[i] = new Point3D[invertedColumns];
for (var j = 0; j < invertedColumns; j++)
result[i][j] = matrix[j][i];
}
matrix.Clear();
matrix.AddRange(result.Select(row => row.ToList()));
Update: (moved first LINQ approach to the bottom since this is much better)
You can use this extension method:
public static List<List<T>> Pivot<T>(this List<List<T>> inputLists, bool removeEmpty, T defaultVal = default(T))
{
if (inputLists == null) throw new ArgumentNullException("inputLists");
if(removeEmpty && !object.Equals(defaultVal, default(T))) throw new ArgumentException("You cannot provide a default value and removeEmpty at the same time!", "removeEmpty");
int maxCount = inputLists.Max(l => l.Count);
List<List<T>> outputLists = new List<List<T>>(maxCount);
for(int i = 0; i < maxCount; i++)
{
List<T> list = new List<T>();
outputLists.Add(list);
for (int index = 0; index < inputLists.Count; index++)
{
List<T> inputList = inputLists[index];
bool listSmaller = inputList.Count <= i;
if (listSmaller)
{
if (!removeEmpty)
list.Add(defaultVal);
}
else
list.Add(inputList[i]);
}
}
return outputLists;
}
Usage:
List<List<int>> lists = new List<List<int>>();
lists.Add(new List<int> { 1 });
lists.Add(new List<int> { 2,3 });
lists.Add(new List<int> { 4,5,6 });
List<List<int>> result = lists.Pivot(true);
foreach(List<int> list in result)
Console.WriteLine(string.Join(",", list));
Output:
1,2,4
3,5
6
Old, accepted version that is less efficient and does not support different default values and removal of empty elements following:
public static List<List<T>> Pivot<T>(this List<List<T>> inputLists)
{
int maxCount = inputLists.Max(l => l.Count);
var result = Enumerable.Range(0, maxCount)
.Select(index => inputLists.Select(list => list.ElementAtOrDefault(index))
.ToList())
.ToList();
return result;
}
Note that it replaces all non existent indices with the default value of that type.
Test:
List<List<int>> lists = new List<List<int>>();
lists.Add(new List<int> { 1 });
lists.Add(new List<int> { 2,3 });
lists.Add(new List<int> { 4,5,6 });
List<List<int>> result = lists.Pivot();
foreach(List<int> list in result)
Console.WriteLine(string.Join(",", list));
Output:
1,2,4
0,3,5
0,0,6
well your input is not of the same length.
what do you expect to see in the first column of the output?
How does your code allow for this?
code should look something like this
List<List<int>> cols = new List<List<int>>();
cols.Add(new List<int>() { 1 });
cols.Add(new List<int>() { 2,3,4 });
cols.Add(new List<int>() { 5,6,7 });
int[][] result = new int[100][];
for (int i = 0; i < cols.Count; i++)
{
for (int j = 0; j < cols[i].Count; j++)
{
if (result[j] == null)
{
result[j] = new int[100];
}
if (cols[i].Count < j)
{
result[j][i] = 0;
} else
{
result[j][i] = cols[i][j];
}
}
}
If you debug your code you should find out easily where exactly is the problem. Probably something like calling 4th column from a 3 column array/list.

c# array help on sorting

First of all sorry for my mistakes in English its not my primary language
i have a problem , i have a array like following
string[] arr1 = new string[] {
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
now i just want to know that how many times Pakistan comes with 1 ,
how many times with 2 , 3 , 4
and i need to know this about all India , USA , Iran , UK
Thanks in advance , you guys are my last hope .
This linq will convert the array into a Dictionary>, where the outer dictionary contains the countries names, and inner dictionaries will contain the ocurrence number (the number after ':') and the count for each ocurrence.
string[] arr1 = new string[]
{
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
var count = arr1
.SelectMany(s => s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(s => s.Split(':')[0], s => s.Split(':')[1])
.ToDictionary(g => g.Key,
g =>
{
var items = g.Distinct();
var result = new Dictionary<String, int>();
foreach (var item in items)
result[item] = g.Count(gitem => gitem == item);
return result;
});
// print the result
foreach(var country in count.Keys)
{
foreach(var ocurrence in count[country].Keys)
{
Console.WriteLine("{0} : {1} = {2}", country, ocurrence, count[country][ocurrence]);
}
}
I would use the String.Split(char[]) method and the String.SubString(int, int) method to inspect every 'country' inside your array and to get the number postfix of each country.
Try the following:
(The following code is now compiled and tested.)
Use a simple data structure to facilitate the task of holding the result of your operation.
public struct Result {
string Country { get; set; }
int Number { get; set; }
int Occurrences { get; set; }
}
// define what countries you are dealing with
string[] countries = new string[] { "Pakistan", "India", "USA", "Iran", "UK", }
Method to provide the overall result:
public static Result[] IterateOverAllCountries () {
// range of numbers forming the postfix of your country strings
int numbersToLookFor = 4;
// provide an array that stores all the local results
// numbersToLookFor + 1 to respect that numbers are starting with 0
Result[] result = new Result[countries.Length * (numbersToLookFor + 1)];
string currentCountry;
int c = 0;
// iterate over all countries
for (int i = 0; i < countries.Length; i++) {
currentCountry = countries[i];
int j = 0;
// do that for every number beginning with 0
// (according to your question)
int localResult;
while (j <= numbersToLookFor) {
localResult = FindCountryPosition(currentCountry, j);
// add another result to the array of all results
result[c] = new Result() { Country = currentCountry, Number = j, Occurrences = localResult };
j++;
c++;
}
}
return result;
}
Method to provide a local result:
// iterate over the whole array and search the
// occurrences of one particular country with one postfix number
public static int FindCountryPosition (string country, int number) {
int result = 0;
string[] subArray;
for (int i = 0; i < arr1.Length; i++) {
subArray = arr1[i].Split(',');
string current;
for (int j = 0; j < subArray.Length; j++) {
current = subArray[j];
if (
current.Equals(country + ":" + number) &&
current.Substring(current.Length - 1, 1).Equals(number + "")
)
result++;
}
}
return result;
}
The following should enable you to run the algorithm
// define what countries you are dealing with
static string[] countries = new string[] { "Pakistan", "India", "USA", "Iran", "UK", };
static string[] arr1 = new string[] {
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
static void Main (string[] args) {
Result[] r = IterateOverAllCountries();
}
The data structure you are using is not rich enough to provide you with that information. Hence you need to parse your string and create a new data structure to be able to provide (sring[][]):
string[] arr1 = new string[] {
"Pakistan,India,USA,Iran,UK",
"Pakistan,India,USA,Iran,UK",
"India,USA,Iran,UK,Pakistan"
};
string[][] richerArray = arr1.Select(x=> x.Split('\'')).ToArray();
var countPakistanIsFirst = richerArray.Select(x=>x[0] == "Pakistan").Count();
UPDATE
You seem to have changed your question. The answer applies to the original question.

Categories

Resources