How to sum array of strings with LINQ Sum method?
I have string which looks like: "1,2,4,8,16"
I have tried:
string myString = "1,2,4,8,16";
int number = myString.Split(',').Sum((x,y)=> y += int.Parse(x));
But it says that cannot Parse source type int to type ?.
I do not want to use a foreach loop to sum this numbers.
You're mis-calling Sum().
Sum() takes a lambda that transforms a single element into a number:
.Sum(x => int.Parse(x))
Or, more simply,
.Sum(int.Parse)
This only works on the version 4 or later of the C# compiler (regardless of platform version)
Instead of
int number = myString.Split(',').Sum((x,y)=> y += int.Parse(x));
use
int number = myString.Split(',').Sum(x => int.Parse(x));
which will parse each element of myString.Split(',') to ints and add them.
var value = "1,2,4,8,16".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select (str => int.Parse(str))
.Sum ( ) ;
Console.WriteLine( value ); // 31
Related
I have a problem with code.
I want to implement radix sort to numbers on c# by using ling.
I give as input string and give 0 in the start of the number:
foreach(string number in numbers){<br>
if(number.lenth > max_lenth) max_lenth = number.lenth;<br><br>
for(int i = 0; i < numbers.lenth; i++){<br>
while(numbers[i].length < max_lenth) numbers[i] = "0" + numbers[i];<br><br>
after this I need to order by each number in string, but it doesn't work with my loop:
var output = input.OrderBy(x => x[0]);
for (int i = 0; i < max_lenth; i++)
{
output = output.ThenBy(x => x[i]);
}
so I think to create a string that contain "input.OrderBy(x => x[0]);" and add "ThenBy(x => x[i]);"
while max_length - 1 and activate this string that will my result.
How can I implement it?
I can't use ling as a tag because its my first post
If I am understanding your question, you are looking for a solution to the problem you are trying to solve using Linq (by the way, the last letter is a Q, not a G - which is likely why you could not add the tag).
The rest of your question isn't quite clear to me. I've listed possible solutions based on various assumptions:
I am assuming your array is of type string[]. Example:
string[] values = new [] { "708", "4012" };
To sort by alpha-numeric order regardless of numeric value order:
var result = values.OrderBy(value => value);
To sort by numeric value, you can simply change the delegate used in the OrderBy clause assuming your values are small enough:
var result = values.OrderBy(value => Convert.ToInt32(value));
Let us assume though that your numbers are arbitrarily long, and you only want the values in the array as they are (without prepending zeros), and that you want them sorted in integer value order:
string[] values = new [] { "708", "4012" };
int maxLength = values.Max(value => value.Length);
string zerosPad = string
.Join(string.Empty, Enumerable.Repeat<string>("0", maxLength));
var resultEnumerable = values
.Select(value => new
{
ArrayValue = value,
SortValue = zerosPad.Substring(0, maxLength - value.Length) + value
}
)
.OrderBy(item => item.SortValue);
foreach(var result in resultEnumerable)
{
System.Console.WriteLine("{0}\t{1}", result.SortValue, result.ArrayValue);
}
The result of the above code would look like this:
0708 708
4012 4012
Hope this helps!
Try Array.Sort(x) or Array.Sort(x,StringComparer.InvariantCulture).
I have a list of strings, each containing a number substring, that I'd like to be reordered based on the numerical value of that substring. The set will look something like this, but much larger:
List<string> strings= new List<string>
{
"some-name-(1).jpg",
"some-name-(5).jpg",
"some-name-(5.1).jpg",
"some-name-(6).jpg",
"some-name-(12).jpg"
};
The number will always be surrounded by parentheses, which are the only parentheses in the string, so using String.IndexOf is reliable. Notice that not only may there be missing numbers, but there can also be decimals, not just integers.
I'm having a really tough time getting a reordered list of those same strings that has been ordered on the numerical value of that substring. Does anyone have a way of doing this, hopefully one that performs well? Thanks.
This will check if the items between the parenthesis is convertible to a double, if not it will return -1 for that case.
var numbers = strings.Select( x => x.Substring( x.IndexOf( "(" ) + 1,
x.IndexOf( ")" ) - x.IndexOf( "(" ) - 1 ) ).Select( x =>
{
double val;
if( double.TryParse( x, out val ) ) {
return val;
}
// Or whatever you want to do
return -1;
} ).OrderBy( x => x ); // Or use OrderByDescending
If you are sure there will always be a number between the parenthesis, then use this as it is shorter:
var numbers = strings.Select(
x => x.Substring( x.IndexOf( "(" ) + 1, x.IndexOf( ")" ) - x.IndexOf( "(" ) - 1 ) )
.Select( x => double.Parse(x))
.OrderBy( x => x ); // Or use OrderByDescending
EDIT
I need the original strings, just ordered on those numbers.
Basically what you need to do is to pass a predicate to the OrderBy and tell it to order by the number:
var items = strings.OrderBy(
x => double.Parse( x.Substring( x.IndexOf( "(" ) + 1,
x.IndexOf( ")" ) - x.IndexOf( "(" ) - 1 ) ));
How about an OO approach?
We are ordering string but we need to treat them like numbers. Wouldn't it be nice if there was a way we can just call OrderBy and it does the ordering for us? Well there is. The OrderBy method will use the IComparable<T> if there is one. Let's create a class to hold our jpg paths and implement the IComparable<T> interface.
public class CustomJpg : IComparable<CustomJpg>
{
public CustomJpg(string path)
{
this.Path = path;
}
public string Path { get; private set; }
private double number = -1;
// You can even make this public if you want.
private double Number
{
get
{
// Let's cache the number for subsequent calls
if (this.number == -1)
{
int myStart = this.Path.IndexOf("(") + 1;
int myEnd = this.Path.IndexOf(")");
string myNumber = this.Path.Substring(myStart, myEnd - myStart);
double myVal;
if (double.TryParse(myNumber, out myVal))
{
this.number = myVal;
}
else
{
throw new ArgumentException(string.Format("{0} has no parenthesis or a number between parenthesis.", this.Path));
}
}
return this.number;
}
}
public int CompareTo(CustomJpg other)
{
if (other == null)
{
return 1;
}
return this.Number.CompareTo(other.Number);
}
}
What is nice about the above approach is if we keep calling OrderBy, it will not have to search for the opening ( and ending ) and doing the parsing of the number every time. It caches it the first time it is called and then keeps using it. The other nice thing is that we can bind to the Path property and also to the Number (we would have to change the access modifier from private). We can even introduce a new property to hold the thumbnail image and bind to that as well. As you can see, this approach is far more flexible, clean and an OO approach. Plus the code for finding the number is in one place so if we switch from () to another symbol, we would just change it in one place. Or we can modify to look for () first and if not found look for another symbol.
Here is the usage:
List<CustomJpg> jpgs = new List<CustomJpg>
{
new CustomJpg("some-name-(1).jpg"),
new CustomJpg("some-name-(5).jpg"),
new CustomJpg("some-name-(5.1).jpg"),
new CustomJpg("some-name-(6).jpg"),
new CustomJpg("some-name-(12).jpg")
};
var ordered = jpgs.OrderBy(x => x).ToList();
You can use this approach for any object.
In the above example code return a list of numbers ordered by numbers but if you want have list of file names that ordered by name better you put in same zero to beginning of the numbers like "some-name-(001).jpg" and you can simply
order that
List<string> strings = new List<string>
{
"some-name-(001).jpg",
"some-name-(005.1).jpg",
"some-name-(005).jpg",
"some-name-(004).jpg",
"some-name-(006).jpg",
"some-name-(012).jpg"
};
var orederedByName =strings.Select(s =>s ).OrderBy(s=>s);
You can make the Substring selection easier, if you first cut off the part starting at the closing parenthesis ")". I.e., from "some-name-(5.1).jpg" you first get "some-name-(5.1". Then take the part after "(". This saves a length calculation, as the 2nd Substring automatically takes everything up to the end of string.
strings = strings
.OrderBy(x => Decimal.Parse(
x.Substring(0, x.IndexOf(")"))
.Substring(x.IndexOf("(") + 1)
)
)
.ToList();
This is probably not of great importance here, but generally, decimal stores numbers given in decimal notation more accurately than double. double can convert 17.2 as 17.19999999999999.
How to create a list of num from 1 to 10
Example:
int[] values = Enumerable.Range(1,max).ToArray();
MessageBox.Show(values+",");
The output should be:
1,2,3,4,5,6,7,8,9,10
Please help
your code is generating array of integers from 1 to 10
int[] values = Enumerable.Range(1,10).ToArray();
but you're displaying them in wrong way (you're trying to cast int array to string), change it to
MessageBox.Show(string.Join(",", values);
string.Join will join your values separating them with ,
In .Net <4.0 you should use (and I believe OP is using one)
MessageBox.Show(string.Join(",", values.Select(x=>x.ToString()).ToArray());
Try like below using the generic version of Join<T>() method.
int[] arr = Enumerable.Range(1, 10).ToArray();
MessageBox.Show(string.Join<int>(",", arr));
Generate 1,2,3,4,5,6,7,8,9,10
(OR) using good old foreach loop
string str = string.Empty;
foreach (int i in arr)
{
str += i.ToString() + ",";
}
MessageBox.Show(str.TrimEnd(','));
List<int> values = Enumerable.Range(1, 10).ToList();
MessageBox.Show(string.Join(",", values.Select(x => x.ToString())));
So what I'm trying to do, is take a job number, which looks like this xxx123432, and count the digits in the entry, but not the letters. I want to then assign the number of numbers to a variable, and use that variable to provide a check against the job numbers to determine if they are in a valid format.
I've already figured out how to perform the check, but I have no clue how to go about counting the numbers in the job number.
Thanks so much for your help.
Using LINQ :
var count = jobId.Count(x => Char.IsDigit(x));
or
var count = jobId.Count(Char.IsDigit);
int x = "xxx123432".Count(c => Char.IsNumber(c)); // 6
or
int x = "xxx123432".Count(c => Char.IsDigit(c)); // 6
The difference between these two methods see at Char.IsDigit and Char.IsNumber.
Something like this maybe?
string jobId = "xxx123432";
int digitsCount = 0;
foreach(char c in jobId)
{
if(Char.IsDigit(c))
digitsCount++;
}
And you could use LINQ, like this:
string jobId = "xxx123432";
int digitsCount = jobId.Count(c => char.IsDigit(c));
string str = "t12X234";
var reversed = str.Reverse().ToArray();
int digits = 0;
while (digits < str.Length &&
Char.IsDigit(reversed[digits])) digits++;
int num = Convert.ToInt32(str.Substring(str.Length - digits));
This gives num 234 as output if that is what you need.
The other linq/lambda variants just count characters which I think is not completely correct if you have a string like "B2B_MESSAGE_12344", because it would count the 2 in B2B.
But I'm not sure if I understood correctly what number of numbers means. Is it the count of numbers (other answers) or the number that numbers form (this answer).
This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5