How can i sort array by name? [duplicate] - c#

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

Related

How to find the index of an element in an array inside a lambda expression in c# [duplicate]

This question already has an answer here:
Index in the Select projection
(1 answer)
Closed 3 years ago.
I want to create a function that flips a string's order
example: "hi" => "ih"
here is the code I have come out with so far:
public static string Flip(this string Str)
{
char[] chararray = Str.ToCharArray();
string output = "";
chararray. //i dont know what methoud should be used to execute action
return output;
}
the thing is, i want to know within the lambda expression what is the index of the object that is currently selected ex:x in (x => x ) indexOf is not an option as there can be more then one char from the same type
how can I know the index?
edit:
I don't want to know how to reverse a string, I want to know how to find an index of an object in lambda expression
In the Select and Where extension methods of LINQ, you have an overload that takes two parameters in the lambda, the first is the element, the second is the index.
so in your case if you have a char array:
var reversedArray = charArray
.Select((c, i) => new { Element = c, Index = i })
.OrderByDescending(arg => arg.Index)
.Select(arg => arg.Element)
.ToArray();
This is just to demonstrate how to get the index in LINQ extesions methods.
As the question states this is not about how to reverse a string.

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;
}

Remove duplicate elements from array, ignoring whitespace [duplicate]

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//",

Sequence multiplication in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there an easy way to return a string repeated X number of times?
In Python you can multiply sequences like this
fivespaces= ' ' * 5
Is there any built-in equivalent for this in C#? (without operator overloads or class extensions)
If it's just a string then you can return multiples by passing in a count to string()
var fivespaces = new string(" ", 5);
In the case where you want a collection of something else like a custom type, you can use Enumerable.Repeat to get a collection:
var items = Enumerable.Repeat(new SomeModel(), 5);

Total sum for an object property value in a list using a lambda function [duplicate]

This question already has answers here:
C# List of objects, how do I get the sum of a property
(4 answers)
Closed 5 years ago.
I have the following: List<OutputRow> which contains a number of OutputRow objects.
I am wondering if there is a way for me to use a lambda function on the list to return the total sum of the values of a certain propertyX on each OutputRow object in the list.
Example list:
OutputRow.propertyX = 4
OutputRow.propertyX = 6
OutputRow.propertyX = 5
return 15
Test data
var ls=new List<OutputRow>();
ls.Add(new OutputRow(){propertyX=4});
ls.Add(new OutputRow(){propertyX=6});
ls.Add(new OutputRow(){propertyX=5});
Lambda
var total= ls.Sum(x=>x.propertyX);
SOmething like this:
var yourSum = yourOutputRowList.Sum(x => x.propertyX);

Categories

Resources