Remove duplicate elements from array, ignoring whitespace [duplicate] - c#

This question already has answers here:
How do I make my string compare not sensitive to (ignore) minor differences in white space?
(4 answers)
Closed 3 years ago.
I've tried several methods to remove duplicate elements from an array of strings, but none of them do what I want. Here are 2 strings:
CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//
CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//
I want just one of these to be retained as they are copied from array a to array b. It doesn't matter which one.
I have tried IEnumerable, HashSet, and Distinct. Each of them returns both strings. (An error of mine duplicated the second string. Sorry. To be clear, I want the compare to ignore whitespace.)
IEnumerable<string> b = a.AsQueryable().Distinct(StringComparer.InvariantCulture);
HashSet<string> set = new HashSet<string>(a);
string[] b = new string[set.Count];
set.CopyTo(b);
string[] b = a.Distinct().ToArray();

The first element isnt the same as the others, so distinct will not gonna work for this, you must replace the space char.
string[] a = { "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//", "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//", "CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NO SPACE//" };
string[] b = a.Select(p => p.Replace(" ", "")).Distinct().ToArray(); //Replace
output:
"CNTY/013121/261538/Y/Y/Y/Y/Y/Y/C/NOSPACE//",

Related

One Way To Match Array of String and List of String [duplicate]

This question already has answers here:
How to compare arrays in C#? [duplicate]
(6 answers)
Closed 2 months ago.
I am trying to match list of string and array string using foreach loop but in my case, it seems I require to iterate a lot to match corresponding values. I've the following:
string[] splitValues = item.ValuesWithComma.Split(',');
So it has indexes and in the same way, the list of string will have the equal indexes. So is it possible to match those directly with indexes as follows to avoid loops:
splitValues == item.lstOfValues;
Right now, I am iterating every time to match and it seems really inappropriate.
foreach (var item in lstOfValues)
{
foreach (var item2 in splitValues )
{
//Condition goes here
}
}
N.B: Both the types may have equal no. of indexes and if unmatched, it'll be skipped. Match means here, the types may have equal no. of values.
You can use bool equal = ls1.SequenceEqual(ls2);, It will match the lists sequentially as well.

C# Sort array using predefined sorted array [duplicate]

This question already has answers here:
Sort String array in custom order
(4 answers)
Fastest way to get list in custom order
(2 answers)
Closed 3 years ago.
How can I sort an array using a predefined sorted array?
I'm working with a web API that you can query for a list of information, which you can specify the things you need in the list. The data list gets returned separated by newlines.
The problem is that the API returns the information in a specific order, regardless of what order you specify yourself.
For example,
Query("second,third,first,fourth");
// returns string:
#"Info for first
Info for second
Info for third
Info for fourth"
I then have to parse it into a dictionary:
{ "first", "Info first" }, {"second", "Info second"}, etc
I could just base it off the parameter list I used, however unless you memorize the correct order for all data, it's a bit annoying.
So, how could I sort it using a predefined sorted list. Such as:
// All possible queries sorted correctly
{ "first", "second", "third", "fourth", "fifth", etc }
// My unsorted list
{ "third", "first", "fifth"}
// Would become:
{ "first", "third", "fifth"}
(These are placeholder values to make it more clear)
You can sort them using a method to compare these results to determine which one comes earlier according to your list
private bool IsBefore(string A, string B)
{
int iA, iB;
iA = Array.IndexOf(RefArray, A);
iB = Array.IndexOf(RefArray, B);
if (A < B)
return true;
return false;
}

How can i sort array by name? [duplicate]

This question already has answers here:
Natural Sort Order in C#
(18 answers)
Closed 6 years ago.
I want to sort it be the number of the names of each file.
The array content is:
0Infrared.jpg
10Infrared.jpg
12Infrared.jpg
14Infrared.jpg
16Infrared.jpg
2Infrared.jpg
4Infrared.jpg
6Infrared.jpg
8Infrared.jpg
But i want it to be ordered like it is on the hard disk:
0Infrared.jpg
2Infrared.jpg
4Infrared.jpg
6Infrared.jpg
8Infrared.jpg
10Infrared.jpg
12Infrared.jpg
14Infrared.jpg
16Infrared.jpg
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.jpg");
Array.Sort(list, (x, y) => String.Compare(x.Name, y.Name));
The variables x and y does not have the properties Name
You have to extract the number, parse it and sort the entire list by this number
string[] sorted = list.Select(x => new {
Item = x,
Number = int.Parse(Regex.Match(x, "[0-9]+").Value) })
.OrderBy(x => x.Number).Select(x => x.Item).ToArray();
Note that this solution assumes that all files start with a number.
You should use a strongly typed collection, like array of FileInfo, you could use DirectoryInfo.GetFiles or similar overload to retrieve such a collection
FileInfo has a name property which you can use in your comparer
The type of sorting that you're doing is called a natural sort

How to get part of a string[] array in C# [duplicate]

This question already has answers here:
How do I clone a range of array elements to a new array?
(26 answers)
Closed 7 years ago.
How, using C#, can I create a new string[] from another string[] containing a subsection of the old string[] array?
For example, if I had:
string[] a = { "cat", "dog", "hamster", "parrot" }
And I wanted to get everything after the first element I should get:
string[] b = { "dog", "hamster", "parrot" }
How, if this is even possible without a for loop, do I achieve this?
You can use some extensions methods to solve it, that is the case for Skip(int) under the System.Linq namespace, for sample:
string[] b = a.Skip(1).ToArray();
And it will skip 1 element and convert the result into a new array. Remember to add the namespace:
using System.Linq;
As the MSDN documentation said:
Bypasses a specified number of elements in a sequence and then returns
the remaining elements.

Split and select specific elements

I have a comma separated string which specifies the indexes. Then I have one more comma separated string which has all the values.
EX:
string strIndexes = "5,6,8,15";
string strData = "ab*bc*dd*ff*aa*ss*ee*mm*jj*ii*waa*jo*us*ue*ed*ws*ra";
Is there a way to split the string strData and select only the elements which are at index 5, 6, 8 or 15. Or will I have to split the string first then loop through the array/list and then build one more array/list with the values at indexes defined by string strIndexes (i.e. 5, 6,7,15 in this example)
Thanks
It's reasonably simple:
var allValues = strData.Split('*')
var selected = strIndexes.Split(',')
.Select(x => int.Parse(x))
.Select(index => allValues[index]);
You can create a list from that (by calling selected.ToList()) or you can just iterate over it.
It depends a bit on the length of the string. If it is relatively short (and therefore any array from "Split" is small) then just use the simplest approach that works; Split on "*" and pick the elements you need. If it is significantly large, then maybe something like an iterator block to avoid having to create a large array (but then... since the string is already large maybe this isn't a huge overhead). LINQ isn't necessarily your best approach here...
string[] data = strData.Split('*');
string[] result = Array.ConvertAll(strIndexes.Split(','),
key => data[int.Parse(key)]);
which gives ["ss","ee","jj","ws"].
call Split(','); on the first string and you get an array of strings, that array you can access by index and the same you can do on the second array. No need to loop array lists.

Categories

Resources