How to sort Strings in C# [duplicate] - c#

This question already has answers here:
C# sort Arraylist strings alphabetical and on length
(5 answers)
Closed 6 years ago.
I have to sort an array of strings. How can I do that, if:
They must be placed in order of string length.
If lengths are equal, the must be placed alphabetically.
Is there any simple to do that ?

Here's the traditional way in C# ...
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("1991728819928891");
list.Add("0991728819928891");
list.Add("3991728819928891");
list.Add("2991728819928891");
list.Add("Hello");
list.Add("World");
list.Add("StackOverflow");
list.Sort(
delegate (string a, string b) {
int result = a.Length.CompareTo(b.Length);
if (result == 0 )
result = a.CompareTo(b);
return result;
}
);
Console.WriteLine(string.Join("\n", list.ToArray()));
}
Sample Output:
Hello
World
StackOverflow
0991728819928891
1991728819928891
2991728819928891
3991728819928891

You can do it with LINQ in the following way:
string[] arr = new[] { "aa", "b", "a" , "c", "ac" };
var res = arr.OrderBy(x => x.Length).ThenBy(x => x).ToArray();
Another way is to use Array.Sort with custom IComparer implementation.

Related

How can I append values in a C# array? [duplicate]

This question already has answers here:
Adding values to a C# array
(26 answers)
Add new item in existing array in c#.net
(20 answers)
Closed 5 years ago.
I need to add values to my array one integer value at a time, via user input.
I don't know how to ask it more clearly, but my goal is to define an integer array in Main(), then pass it to Interactive() where a user is supposed to enter 20 different ints and the program should add them to the array.
It would be tedious to continue defining new arguments for each object (like this):
int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]
because I am filling 20 array objects, surely there is an easier way?
Can someone help?
Here is the code I am working with:
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[20];
}
public static int[] Interactive(int[] args)
{
int[] ArrayOne = new int[20];
Write("\n Write an integer >>");
ArrayOne[0] = Convert.ToInt32(ReadLine());
foreach (int x in ArrayOne)
{
if (x != ArrayOne[0])
Write("\n Write another integer");
ArrayOne[x] = Convert.ToInt32(ReadLine());
WriteLine("\n {0}", ArrayOne[x]);
}
ReadLine();
return ArrayOne;
}
}
Try using a List. Unlike arrays their size can be dynamically changed.
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>();
numbers.add(1);
numbers.add(2);
}
}
Are you looking for this?
int[] intArray = Interactive(values here);
public static int[] Interactive(int[] args)
{
//TODO:
}

Verify that a list has all the other list values [duplicate]

This question already has answers here:
Does .NET have a way to check if List a contains all items in List b?
(5 answers)
Closed 7 years ago.
I have 2 int arrays, arr1, and arr2 eg, what is the most efficient way to verify that the arr1 contains All items that arr2 contains. Preferentially returning bool.
eg.
arr1 = [1,2,3,4]
arr2 = [1,2,3,4,5,6,9]
//return true;
arr1 = [1,2,3,4,10]
arr2 = [1,2,3,4,5,6,9]
//return false;
I did It with foreach but I want anything besides brute-force foreach, if is possible.
What about something like:
bool subset = !arr1.Except(arr2).Any();
Would probably be smoothly implemented as an extension method like this:
public static bool ContainsAll<T>(this List<T> list, List<T> other)
{
return !other.Except(list).Any();
}
Usage would then be:
bool subset = arr2.ContainsAll(arr1);

Sort a List<string[]> by the second value (int) [duplicate]

This question already has answers here:
How to Sort a List<T> by a property in the object
(23 answers)
Closed 7 years ago.
I have a list
List<string[]> listname = ...
The list looks like this:
[string][string][string]
I want to sort the list by second string.
The second string is a number presented as a string, i want to keep it that way, i need it like this.
I want the numbers to be in Increasing order.
Example for data:
["RDP"]["3389"]["TCP"]
["HTTP"]["80"]["TCP"]
["HTTPS"]["443"]["TCP"]
I want to sort by the post number.
In this example "RDP" will become the last one.
How can I do so?
var sortedList = listname.OrderBy(l => int.Parse(l[1]));
This assumes that the second entry in each array is parsable as int. If you're not sure about that, you'd need to add some checks and maybe use int.TryParse.
You can refer to appropriate index of an array in OrderBy:
var l = new List<string[]>() {
new string[] { "a", "b", "c" },
new string[] { "b", "a", "c" },
new string[] { "c", "c", "c" },
};
var s = l.OrderBy(c => c[1]).ToList();

Is there a Linq method to tell that A is the subset of B? [duplicate]

This question already has answers here:
Check whether an array is a subset of another
(10 answers)
Closed 8 years ago.
Let's I have 2 arrays string[] A = { "a", "b", "c" } and string[] B = { "a", "b", "c", "d", "e" }.
Is there any method that can tell directly that A is a subset of B? Except will just remove distinct elements of B, but won't tell whether it's completely a subset of B.
Thank you for helping.
you can do this,simply:
A.All(B.Contains);
And you may wanna check the Length to make sure they are not the same size and A is a subset
bool isSubset = A.All(B.Contains) && A.Length < B.Length;
There's even a method for this purpose. You could use HastSet<T>.IsSubsetOf:
var aSet = new HashSet<string>(A);
bool isASubsetOfB = aSet.IsSubsetOf(B);
This should work
bool isSubSet = !A.Except(B).Any();
You can combine SequenceEquals and Intersect:
var isASubsetOfB = B.Intersect(A).SequenceEqual(A)

Is there any way to initialize several variables from one array? [duplicate]

This question already has answers here:
c# multi assignment
(7 answers)
Closed 8 years ago.
In some languages it is possible to initialize several variables at the same time from an array.
For example in PHP you can do something like this:
$array = array('a', 'b', 'c');
list($a, $b, $c) = $array;
Is it possible to do this in C# as well?
I want to apply this on a program where I read all lines from a file where I know every line is two words only (never more, never less).
I know I can create the function myself (and sending in variables by reference with outkeyword) but I would like to know if any built in functionality exists for it.
I would like to know this mostly for the reason that if it is possible the code might be more readable for other developers.
In C#,
string[] arr1 = new string[] { "one", "two", "three" };
string s1 = arr1[0];
string s2 = arr1[1];
string s3 = arr1[2];
If readability is the issue and if I understand you correctly - I don't know of an in-built way. But you can create a function for that.
void Doit(out string one, out string two, string[] input)
{
one = input[0];
two = input[1];
}
And use it thus:
string[] s = new string[] { "First", "Second" };
string a, b;
Doit(out a, out b, s);
I just realized that you don't need my answer. (I had initially understood "I know I can create the function myself..." differently.) Perhaps, though, it can help someone else.
char[] array = new char[] {'a','b','c'};
As far as I know there is no buit-in way to do that.
Maybe a good way to implement that functionality is by using extension methods in order to improve readability.
Simply write the needed code in a extension method that can be attached to the type you want to initialize like a list in your example above and take an array as input to that function:
public static class Extensions {
public static void initFromArray<T> (this List<T> list, T[] array) {
for (int i = 0; i < array.Length; i++) {
list[i] = array[i];
}
}
}
Then you can use this method for example like in the following:
int[] array = new int [] { 1, 4, 6, 2, 5 };
List<int> list = new List<int>();
for (int i = 0; i < 4; i++) list.Add(0);
list.initFromArray<T>(array);

Categories