I got a simple IEnumerable with some data in my debugging session for StockSearchList. How do I convert to a List but ToList is not accespted.
public IEnumerable<StockSearchItemViewModel> StockSearchList
{
get
{
if (string.IsNullOrEmpty(_stockSearchFilter))
return _stockSearchList;
var filterLower = _stockSearchFilter.ToLower();
return _stockSearchList.Where(x => { var symbolLower = x.Symbol.ToLower(); return (symbolLower.StartsWith(filterLower) || symbolLower.StartsWith(filterLower)); });
}
}
In another method i got:
List<StockTickerData> ssl = new List<StockTickerData>();
ssl = StockSearchList<StockTickerData>.ToList();
But I get build error of:
Error 4 The property 'xxxx.StockViewModel.StockSearchList' cannot be used with type arguments .... stockviewmodel.cs 838 19
How do I convert ssl to a be list from the values in StockTickerData
Thanks
It is just a simple syntax error, the right code:
List<StockTickerData> ssl = StockSearchList.ToList();
Related
I've already implemented integration with Selenium -- Testrail. Everything was correct until today when I'm keep receiving:
OneTimeSetUp: System.InvalidCastException : Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
Here is the line of code where it fails:
JArray getListOfAllActiveTestRun = (JArray)client.SendGet($"get_runs/{ProjectId}");
As I'm assuming I need to have a JArray to use it later inside foreach loop (Full code view)
if (RunId == null)
{
JArray getListOfAllActiveTestRun = (JArray)client.SendGet($"get_runs/{ProjectId}");
foreach (JObject testRun in getListOfAllActiveTestRun)
{
bool isCompleted = Convert.ToBoolean(testRun["is_completed"]);
string lastTestRunId = testRun["id"].ToString();
string lastSuiteId = testRun["suite_id"].ToString();
int failedTestCount = testRun["failed_count"].Value<int>();
int untestedTestCount = testRun["untested_count"].Value<int>();
if (!isCompleted && lastSuiteId.Equals(SuitId) && failedTestCount > 0 || !isCompleted && lastSuiteId.Equals(SuitId) && untestedTestCount > 0) // we are checking that there is not finished testRun with suitId equal to this and failed tests and untested tests
{
RunId = lastTestRunId;
break;
}
}
}
Checked the solutions and most of the time I was facing option with JsonConvert.DeserializeObject but I'm not sure if this is correct hint in my case.
Edit (JSON)
"runs":
{
"id":2874,
"suite_id":878,
"name":"[ENV: TEST] [BACKOFFICE] Automation Test Run - [20:02:55 PM]",
"description":null,
"milestone_id":null,
"assignedto_id":null,
"include_all":true,
"is_completed":false,
"completed_on":null,
"config":null,
"config_ids":[
],
"passed_count":171,
"blocked_count":0,
"untested_count":1,
"retest_count":0,
"failed_count":3,
"custom_status1_count":0,
"custom_status2_count":0,
"custom_status3_count":0,
"custom_status4_count":0,
"custom_status5_count":0,
"custom_status6_count":0,
"custom_status7_count":0,
"project_id":19,
"plan_id":null,
"created_on":1631901776,
"updated_on":1631901776,
"refs":null,
"created_by":124,
"url":"ssss"
}
I've been encountering the same problem starting from today as well -- it seems like there's been a change in TestRail's API.
From TestRail's API reference: "...These bulk endpoints will no longer return an array of all entities, but will instead return an object with additional pagination fields and an array of up to 250 entities."
Source: https://www.gurock.com/testrail/docs/api/reference/runs#getruns
I have a multiselectlist where a user can pick some or none inputvoltages. When the user selects no InputVoltages my query throws a null exception when I call .Tolist(). Why am I not just getting back an empty list?
I'm using MVC5 C# and entity framework 6.
repository
public IQueryable<InputVoltage> All
{
get { return context.InputVoltages; }
}
controller
var newInputVoltages = unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages
.Contains(m.Id))
.ToList<InputVoltage>();
All does return a list but SelectedInputVoltages is null when nothing is selected. I was wondering if that was the issue.
When I use this query and add a where statement for my index page I don't receive a null error when I call ToList
IQueryable<EngineeringPdsIndexViewModel> query =
(from a in context.EngineeringPds
select new EngineeringPdsIndexViewModel
{
Id = a.Id,
Name = a.Name,
Status = a.Status,
AnnualQuantities = a.AnnualQuantities,
ToMarketDate = a.ToMarketDate,
SubmittedBy = a.SubmittedBy,
TargetPrice = a.TargetPrice
});
So I believe Brian has the right idea of what is wrong but here is the issue extended
I have a multiselect box that is populated in the get action method by
IList<InputVoltage> inputVoltagesList = unitOfWorkPds.InputVoltageRepository.All.ToList();
then
pdsEditViewModel.InputVoltageList = inputVoltagesList.Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() }); in my view I hav#Html.ListBoxFor(m => m.SelectedApprovals, Model.ApprovalList)
but when a user makes no selections the selectedInputvoltages comes into my post controller action as null how do I get it to come in as an empty list?
UPDATE
For anyone who runs into the same problem Brians first answer explains the issue. The work around for submitting a ListBox with empty lists can be found here
How can I return an empty list instead of a null list from a ListBoxFor selection box in Asp.net MVC?
Any Extension method defined in the BCL for IEnumerable<T> or IQueryable<T> that returns IEnumerable<T> or IQueryable<T> will not return null. It might return an empty collection, but that is very different to null.
try this:
var newInputVoltages = engineeringPdsEditViewModel.SelectedInputVoltages == null ?
unitOfWorkPds.InputVoltageRepository.All :
unitOfWorkPds.InputVoltageRepository.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id)).ToList();
Where will not return null. The problem is in the argument:
engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id)
A NULL engineeringPdsEditViewModel or SelectedInputVoltages can cause NullReferenceException to be thrown. So you need to do a null check against these objects.
You can see this play out with a similar test sample. Here we get a nullrefex because myString is null. So when Where executes it tries to do a comparison and blows up:
var test = new TestClass(1);
var test2 = new TestClass(2);
var test3 = new TestClass(3);
List<TestClass> tests = new List<TestClass>();
tests.Add(test);
tests.Add(test2);
tests.Add(test3);
string myString = null;
var result = tests.Where(t => myString.Contains(t.Myint.ToString())).ToList();
Console.WriteLine(result.Count);
Update: (To answer your comment)
You can return an empty list like this:
List<InputVoltage> newInputVoltages = new List<InputVoltage>();
if(engineeringPdsEditViewModel != null && engineeringPdsEditViewModel.SelectedInputVoltages != null)
{
//Where params are not null so its safe to use them
newInputVoltages = unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages
.Contains(m.Id))
.ToList<InputVoltage>();
}
//else no need to do anything...just return the empty list created above
return newInputVoltages;
you will not get an empty list and it's expected behaviour it returns null.
just test the input (I used the Ternary Operator) when you create the variable and you won't need any validation later
var newInputVoltages = SelectedInputVoltages.Any()
? unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id))
.ToList<InputVoltage>()
: new List<InputVoltage>();
Below is my code which gives an error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'string[]'
I tried several times to solve the error. But I failed to do so.
if any body can suggest what could be the solution.. Thanks :)
public GetContentResponse GetContent(abcServiceClient client, QueryPresentationElementIDsResponse querypresentationelementresponse)
{
GetContentRequest GetContentRequest = new GetContentRequest();
GetContentResponse contentresponse = new GetContentResponse();
querypresentationelementresponse = presentationElementId(client);
List<string[]> chunks = new List<string[]>();
for (int i = 0; i < querypresentationelementresponse.IDs.Length; i += 25)
{
chunks.Add(querypresentationelementresponse.IDs.Skip(i).Take(25).ToArray());
contentresponse = client.GetContent(new GetContentRequest()
{
IDs = chunks // here i get this error
});
}
return contentresponse;
}
You're trying to assign a List to a string array. Convert the list to an array.
Since you haven't specified exactly where the error was I suppose it's when you're assign the IDs variable.
The following code would solve it:
public GetContentResponse GetContent(abcServiceClient client, QueryPresentationElementIDsResponse querypresentationelementresponse)
{
GetContentRequest GetContentRequest = new GetContentRequest();
GetContentResponse contentresponse = new GetContentResponse();
querypresentationelementresponse = presentationElementId(client);
List<string> chunks = new List<string>();
for (int i = 0; i < querypresentationelementresponse.IDs.Length; i += 25)
{
chunks.AddRange(querypresentationelementresponse.IDs.Skip(i).Take(25));
contentresponse = client.GetContent(new GetContentRequest()
{
IDs = chunks.ToArray()
});
}
return contentresponse;
}
I'm not sure what type IDs is or what line is giving you that error, but if I had to guess, I think its IDs = chunks.
It sounds like you are trying to convert a list to a string array. You need to use a method to convert using toArray().
Edit: Ok, you have an array of string arrays. You need to grab the correct one with:
IDs = Chunks.ToArray()[index]
Where index is the correct array. Not terribly familiar with the libraries you are working with, so I unfortunately cannot elaborate. However, to take a wild guess, try using i in place of index.
I think I understand returning records of an anonymous type from But in this I want to create NEW CatalogEntries, and set them from the values selected. (context is a Devart LinqConnect database context, which lets me grab a view).
My solution works, but it seems clumsy. I want to do this in one from statement.
var query = from it in context.Viewbostons
select it;
foreach (GPLContext.Viewboston item in query)
{
CatalogEntry card = new CatalogEntry();
card.idx = item.Idx;
card.product = item.Product;
card.size = (long)item.SizeBytes;
card.date = item.Date.ToString();
card.type = item.Type;
card.classification = item.Classification;
card.distributor = item.Distributor;
card.egplDate = item.EgplDate.ToString();
card.classificationVal = (int)item.ClassificationInt;
card.handling = item.Handling;
card.creator = item.Creator;
card.datum = item.Datum;
card.elevation = (int)item.ElevationFt;
card.description = item.Description;
card.dirLocation = item.DoLocation;
card.bbox = item.Bbox;
card.uniqID = item.UniqId;
values.Add(card);
}
CatalogResults response = new CatalogResults();
I just tried this:
var query2 = from item in context.Viewbostons
select new CatalogResults
{ item.Idx,
item.Product,
(long)item.SizeBytes,
item.Date.ToString(),
item.Type,
item.Classification,
item.Distributor,
item.EgplDate.ToString(),
(int)item.ClassificationInt,
item.Handling,
item.Creator,
item.Datum,
(int)item.ElevationFt,
item.Description,
item.DoLocation,
item.Bbox,
item.UniqId
};
But I get the following error:
Error 79 Cannot initialize type 'CatalogService.CatalogResults' with a
collection initializer because it does not implement
'System.Collections.IEnumerable' C:\Users\ysg4206\Documents\Visual
Studio
2010\Projects\CatalogService\CatalogService\CatalogService.svc.cs 91 25 CatalogService
I should tell you what the definition of the CatalogResults is that I want to return:
[DataContract]
public class CatalogResults
{
CatalogEntry[] _results;
[DataMember]
public CatalogEntry[] results
{
get { return _results; }
set { _results = value; }
}
}
My mind is dull today, apologies to all. You are being helpful. The end result is going to be serialized by WCF to a JSON structure, I need the array wrapped in a object with some information about size, etc.
Since .NET 3.0 you can use object initializer like shown below:
var catalogResults = new CatalogResults
{
results = context.Viewbostons
.Select(it => new CatalogEntry
{
idx = it.Idx,
product = it.Product,
...
})
.ToArray()
};
So if this is only one place where you are using CatalogEntry property setters - make all properties read-only so CatalogEntry will be immutable.
MSDN, Object initializer:
Object initializers let you assign values to any accessible fields or properties of an
object at creation time without having to explicitly invoke a constructor.
The trick here is to create a IQueryable, and then take the FirstOrDefault() value as your response (if you want a single response) or ToArray() (if you want an array). The error you are getting (Error 79 Cannot initialize type 'CatalogService.CatalogResults' with a collection initializer because it does not implement 'System.Collections.IEnumerable') is because you're trying to create an IEnumerable within the CatalogEntry object (by referencing the item variable).
var response = (from item in context.Viewbostons
select new CatalogEntry()
{
idx = item.Idx,
product = item.Product,
size = (long)item.SizeBytes,
...
}).ToArray();
You don't have to create anonymous types in a Linq select. You can specify your real type.
var query = context.Viewbostons.Select( it =>
new CatalogEntry
{
idx = it.idx,
... etc
});
This should work:
var query = from it in context.Viewbostons
select new CatalogEntry()
{
// ...
};
My Db column in a string (varchar) and i need to assign it to a int value.
I am using linq to query.Though the code compiles am getting an error at the run time .
Thanks in advance.
PFB my query :
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
//(Int32)plan.cap_group_code,
Value = plan.cap_group_name
};
return vlauesCap.ToList();
The EF provider does not know how to translate Convert.ToInt() into SQL it can run against the database. Instead of doing the conversion on the server, you can pull the results back and do the conversion using linq to objects:
// the ToList() here causes the query to be executed on the server and
// the results are returned in a list of anonymous objects
var results = (from plan in entities.PA_RTM_CAP_Group
select new
{
Code = plan.cap_group_code,
Name = plan.cap_group_name
}).ToList();
// the conversion can now be done here using Linq to Objects
var vlauesCap = from r in results
select new Business.PartnerProfile.LookUp
{
Id = Convert.ToInt32(r.Code),
Value = r.Name
};
return vlauesCap.ToList();
You can't do this directly, what you can do is declare a private variable to handle your "mapped" value, and expose the unmapped property...
[Column(Name = "cap_group_code", Storage = "m_cap_group_code")]
private string m_cap_group_code;
public int cap_group_code {
get
{
return Int32.Parse(m_cap_group_code);
}
set
{
m_cap_group_code = value.ToString();
}
}
Try this:
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
Convert.ToInt32(plan.cap_group_code),
Value = plan.cap_group_name
};
return vlauesCap.ToList();
Why aren't you using casting for such a purpose, which is a more effective way of achieving this.
Just replace Convert.ToInt32(plan.cap_group_code) with (int)plan.cap_group_code
Do remember, there should be a value in the string and is int, else it will show Exception. If you are not sure about it, then you can further expand the casting to use null coalesciting operator