This question already has answers here:
Find character with most occurrences in string?
(12 answers)
Closed 7 years ago.
I'm trying to find a clever way using linq to examine an IEnumerable and find the max occurrences of some element.
"aba".SomeLinqExpression(); // => 'a'
or
(new List<int>{1, 2, 3, 4, 1, 2, 1}).SomLinqExpression(); // => 1
Is there an easy built in way to do this I think I need an aggregation query but Aggregate and Count don't seem to do it. Maybe groupby?
EDIT: Clarification
I'm looking to get access to the most often seen value. I don't care how ties are handled.
if we have a string
"abcda" // note that there are 2 'a' characters.
Since 'a' is the most common thing in the sequence I want this operation to return 'a'
"abcda".SomeLinqExpression(); // returns 'a'
Well, I guess this will work:
"aqejqkndaasaamd".GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key
Related
This question already has answers here:
LINQ Query How to select Max value between start and end index and the index of the max value
(2 answers)
How can I get LINQ to return the index of the object which has the max value in a collection?
(2 answers)
How to use LINQ to select object with minimum or maximum property value
(20 answers)
How to perform .Max() on a property of all objects in a collection and return the object with maximum value [duplicate]
(9 answers)
What is faster in finding element with property of maximum value [duplicate]
(5 answers)
Closed 1 year ago.
In a List<float[]> containing arrays of varying sizes, I want to find the Index of that array whose length is maximum in the List.
I'm using the following LINQ statement:
var index = list
.Select((arr, ind) => new { arr, ind })
.Where(x => x.arr.Length == list.Max(a => a.Length))
.Select(x => x.ind)
.ToList()
.First();
This seems to work but the query is returning a list of elements whose Length is equal to list.Max(a => a.Length) where after I have to use .First() to get the first Maximum Index.
Is there any more efficient way to do this so that I directly get the index value rather than a List to avoid use of First?
EDIT: As the question was marked duplicate, I want to clarify that I do not want the object in return but the index of that object itself. I've gone through all the posts that my question can be a potential duplicate of and found that they are all returning the object of Max Length. Though the difference is very thin but I believe my question is not a duplicate.
EDIT: After running a few test and measuring the time taken by each LINQ Satements submitted,Below is the table with time taken (in milliseconds) by each method during my tests
Test
Max
Aggregate
GroupBy
GroupBy OrderByDescending
First
13.5946
1.8927
7.3801
7.1061
Second
12.3544
1.9245
7.4852
7.1755
Third
12.1003
1.8772
7.3531
6.6891
Its easy to understand that Aggregate method given by Dmitry Bychenko is working far efficiently than any other used methods in this situation. Tim Schmelter's GroupBy and OrderByDescending Answer is also doing the same job but taking more time than Aggregate. Furthermore I wanted to avoid using First. Hence, I feel the Aggregate method is an appropriate solution for my question.
You can try general aggregating method Aggregate instead of specific Max:
var index = list
.Select((array, index) => (array, index))
.Aggregate((s, a) => s.array.Length > a.array.Length ? s : a)
.index;
This question already has answers here:
Is there a string math evaluator in .NET?
(18 answers)
how to convert a string to a mathematical expression programmatically
(6 answers)
Closed 2 years ago.
I want to calculate a string in C# using either NCalc or DynamicExpresso library, the problem is, when the calculation gets complex and the numbers are big, it returns the wrong result.
For example the code below returns -808182895 when it should return 3486784401
string value = "387420489*9";
value = new Interpreter().Eval(value).ToString();
Am i doing anything wrong?
Thanks for the help.
Try the following:
(long)387420489 * (long)9
Dynamic Expresso has a web shell here where you can test the expressions;
http://dynamic-expresso.azurewebsites.net/
While testing on this web shell, I realized that;
387420489L * 9 => Syntax error (at index 9). => does not accept type suffix
(long)387420489 * 9 => -808182895 => overflow
387420489 * (long)9 => 3486784401 => OK
2147483647 + 1 => -2147483648 => int.MaxValue + 1 = int.MinValue (overflow)
2147483648 + 1 => 2147483649 => When does not fit into Int32, interpreted as long
While most of these can be regarded as by design (considering how Dynamic Expresso evaluates the statement), there can still be further improvement.
Think of Javascript for example.
387420489*9 => 3486784401
The question is, is what we need
to execute the given arithmetic expression correctly, as we and the end-user expects,
to execute the given arithmetic expression the C# way?
The former, I think.
This question already has answers here:
How to perform .Max() on a property of all objects in a collection and return the object with maximum value [duplicate]
(9 answers)
Closed 5 years ago.
What I want to do is basically
var max = things.Select(t => ExpensiveFunc(t)).Max();
var ThingWithMaxResult = things.Where(t => ExpensiveFunc(t) == max).First();
But I don't want to have to run the ExpensiveFunc twice on each element.
I am learning LINQ so I would like to know the LINQ way of doing this. Otherwise I would normally create an array of things and results, then just pick the array with the highest result.
You can order by the function call (descending) and take the first one:
var max = things.OrderByDescending(ExpensiveFunc).First();
This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 7 years ago.
I already tried to determinate the digits in a sentence using 'isDigit', but this gives me a 'bool' output. I need an 'int' output.
What i want to do is, say, i have the sentence "cheese23"; "2" and "3" will be put in their own variable, so i can add/subtract/multiply/ etc them.
(x=2,y=3;)
help will be hugely appreciated (self-teaching beginner here)
Do:
int[] intArray = "Cheese23".Where(Char.IsDigit).Select(c => int.Parse(c.ToString())).ToArray();
This extracts the numbers in the string in the order and creates an array out of it.
Then you can do intArray[0] to get 2 and intArray[1] to get 3.
Search up LINQ to see how those chain of methods did it.
This question already has answers here:
Natural Sort Order in C#
(18 answers)
Closed 6 years ago.
What's the easiest way to get a LINQ query (from an SQL database - does that matter?) to order strings naturally?
For example, I'm currently getting these results:
Project 1
Project 10
Project 2
What I'd like is to see is this:
Project 1
Project 2
Project 10
The query I'm using is this:
return from p in dataContext.Projects
orderby p.Name
select p;
There is no built-in way to do this using the .NET framework but I would suggest that you read Natural Sorting in C# for a discussion on the topic and an open-source implementation.
I'm only a few years late to the party, but I was just trying to solve a similar problem and this worked for me. Hope someone else finds this helpful.
Say you have your strings in a List, try something like this:
List<string> projects = new List<string>
{
"Project 1",
"Project 10",
"Project 2"
};
//Sort by a substring of the string value which omits the non-numeric characters
IEnumerable<string> sorted = projects.OrderBy(p => p.Substring(p.IndexOf(' ') + 2, p.Length - (p.IndexOf(' ') + 2)));