I have a string:
private const string Codes = "2,10";
public void method()
{
var displayCodes = Codes.Split(',');
DemoResponse response = webService.GetResponse(); //getting response from API
if(response.Errors.Any(x => displayCodes.Contains(x.StackTrace))
{
int myCode = int.Parse(response.Errors.Select(x => x.StackTrace).FirstOrDefault());
}
}
This is the "DemoResponse" model:
public class DemoResponse
{
public bool Validate { get; set; }
public IEnumerable<ErrorResponse> Errors { get; set; }
}
public class ErrorResponse
{
public string Message { get; set; }
public string StackTrace { get; set; }
}
The DemoResponse "response" from the API returns result as: (for example)
{
"Validate" : false,
"Errors" :
{
"Message" : "test1",
"StackTrace" : "2"
}
}
{
"Validate" : false,
"Errors" :
{
"Message" : "test1",
"StackTrace" : "2"
}
}
{
"Validate" : false,
"Errors" :
{
"Message" : "test1",
"StackTrace" : "95"
}
}
The DemoResponse "response" will always contain only one of the code from const string "Codes", i.e either 2 or 10. But may contain other codes.
If the DemoResponse "response" contains the code 2 as the first Code, then this line works fine:
int myCode = int.Parse(response.Errors.Select(x => x.StackTrace).FirstOrDefault());
But if the DemoResponse "response" does not have code 2 as first, then how do I write a LINQ to select Code 2 and assign to "myCode" variable?
For example:
"StackTrace" : "95",
"StackTrace" : "95",
"StackTrace" : "2"
2
Answers
Need to add for each loop inside if condition.
It seems to me that what you want to receive form the API is an array of information, but in your code you are mapping what you receive from the API into a single object of type
DemoResponse
. I suspect that you actually wantresponse
to be a list or array ofDemoResponse
s.Furthermore, from my understanding of the following question:
, you want to assign the first
StackTrace
value that matches any of the codes inCodes
, tomyCode
; rather than assigning anyStackTrace
value tomyCode
.If those two assumptions are correct, you could try the following:
Alternatively, you could look loop through the stack traces rather than the errors: