I need to fetch the result of the List by using 2 Where Conditions and GroupBy Condition.
The Query which worked to achive part of the solution is
var errorQuery = AgentOpList.Where(x => x.LastError != "")
.GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
But now, i should also include another condition in the list, so the condition is x.Status != "FINISHED"
So the final query which i tried was
var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
.GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
However, it throws me the error
Index and length must refer to a location within the string. Parameter name: length
I know the reason for this error. However, i would like to know the solution.
LastError
is shorter than 30 characters.
If you're using linq to objects, you could create a new function:
public bool TakeChars(string str, int chars) {
if (str.Length < 30) { return str; }
else return str.Substring(0,30);
}
And then use it:
var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
.GroupBy(x => TakeChars(x.LastError, 30)).ToArray();
If you don't want to create a new function or you're using linq to sql, I think this would work (@FCin):
var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
.GroupBy(x => x.LastError.Substring(0, Math.Min(30, x.LastError.Length))).ToArray();
Also, a small improvement to your Where
:
var errorQuery = AgentOpList.Where(x => !string.IsNullOrEmpty(x.LastError) || x.Status != "FINISHED")
.GroupBy(x => .... ).ToArray();
Make sure Substring
never receives a string shorter than 30 characters by padding it with trailing spaces:
var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
.GroupBy(x => x.LastError.PadRight(30, ' ').Substring(0, 30)).ToArray();
(Assuming this is LINQ to objects as SQL's SUBSTRING
wouldn't throw an exception).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.