how can convert var to List c# - c#

I would like to convert var to list value . I am getting 'myobj' var value. Now how can i convert to CandidateResume list ?.
JavaScriptSerializer jsSerializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };
var myobj = jsSerializer.Deserialize<List<List<CandidateResume>>>(description);
My CandidateResume class like this
public class CandidateResume
{
public string name { get; set; }
public string url { get; set; }
public string summary { get; set; }
public string role { get; set; }
public string compensation { get; set; }
public string education { get; set; }
public string expertise { get; set; }
public string years { get; set; }
public string relocation { get; set; }
public string resume { get; set; }
public string resumeExtension { get; set; }
public string resumeMimeType { get; set; }
}
Please see this current item value in screenshot
How can i catch item value ?
foreach (var item in myobj)
{
WebScrappingCandidate webScrappingCandidate = new WebScrappingCandidate();
}

Deserialize<T> returns a T (MSDN), which means myObj is already of type: List<List<CandidateResume>>.
Remember, var is not a type, it just uses type inference to be shorthand for: "Be whatever type I'm being assigned to".
To "flatten" this list, you could just use SelectMany:
foreach (CandidateResume resume in myObj.SelectMany(i => i))
{
}
Of course, there are other methods as well, but the crux of the answer is that you already have a list of candidate resumes. No conversion required.

You already have a list, the Deserialize method returns a typed result:
List<List<CandidateResume>> myobj =
jsSerializer.Deserialize<List<List<CandidateResume>>>(description);
When you loop through that, each item is a list:
foreach (List<CandidateResume> item in myobj) {
...
}

Related

How to compare object and List<> and object.value null when the value doesn't exist in list

I need to compare between my object and a list.
List contains attribute "nom_colonne", it fill by a query and the result is a list of attributes (same like my object AppareilsReparations)
For example :
if droit_utilisateur.nom_colonne = "Num_dossier"
so i keep the value in arp.num_dossier
But if i don't have this value of my list droit_utilisateur :
arp.num_dossier will be null.
I wanted to cast my object with System.Collections.IList but impossible to cast. I have an error.
public class AppareilsReparations
{
public string Num_dossier { get; set; }
//public string reference_aff { get; set; }
public int Id { get; set; }
public Guid Uid { get; set; }
public string ref_sav { get; set; }
public CodeDefaut codedefaut { get; set; }
public CodeSymptome codesymptome { get; set; }
}
public class Droits
{
public int id { get; set; }
public int utilisateur_id { get; set; }
public string nom_table { get; set; }
public string nom_colonne { get; set; }
}
AppareilsReparations arp = db.Query<AppareilsReparations>
("select * from v_appareils_reparations where ref_sav_client =#ref_sav", new { ref_sav }).SingleOrDefault();
List<Droits> droit_utilisateur = GetDroits("admin");
//var appareil = new List<AppareilsReparations>();
IList appareil = (IList)arp;
var result = droit_utilisateur.Where(x => !appareil.Contains(x.nom_colonne)).ToList();
That's cause AppareilsReparations is not a type of IList and thus your cast would always fail IList appareil = (IList)arp;. Probably you wanted to do like below; just comparing with Num_dossier field of AppareilsReparations type
var result = droit_utilisateur.Where(x => x.nom_colonne == arp.Num_dossier).ToList();
i have found my problem, i post my code for everybody :
List<Droits> droit_utilisateur = GetDroits(username);
Type myType = e.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in e.GetType().GetProperties())
{
object propValue = prop.Name;
if (droit_utilisateur.Any(s => s.nom_colonne.Contains(prop.Name/*, StringComparison.OrdinalIgnoreCase)*/) == false))
{
prop.SetValue(e, Convert.ChangeType(null, prop.PropertyType), null);
}
}
return e;

Remove an object from a list based on an attribute of another list with linq

I have the following class to store objects from a REST API call from SharePoint:
[Serializable]
public class DocumentSearchResult
{
public string TotalCount { get; set; }
public string DocumentPath { get; set; }
public string DocumentTitle { get; set; }
public string DocumentSize { get; set; }
public string DocumentAuthor { get; set; }
public string DocumentDescription { get; set; }
public string DocumentFileExtension { get; set; }
public double DocumentRank { get; set; }
public Int64 DocumentDocId { get; set; }
public Int64 DocumentWorkId { get; set; }
public DateTime DocumentWrite { get; set; }
public string DocumentParentLink { get; set; }
public DateTime DocumentLastModifiedDate { get; set; }
public string DocumentFileType { get; set; }
//These next set of properties are used for Viewing the results in embedded or preview
public string DocumentRedirectedEmbededURL { get; set; }
public string DocumentRedirectPreviewURL { get; set; }
public string DocumentRedirectURL { get; set; }
}
I create a list of these objects in my code:
var docReturnResult = new List<DocumentSearchResult>();
I have another list I create using:
var filterList = this.Where(x => x.TenantId == TenantId);
this will return an IQueryable list that contains a value I need to filter the second list. The filterList has an attribute called SharePointId (x => x.SharePointId) that I need to use to filter the docReturnResult list. So I need to compare the filterList SharePointId to the docReturnResult DocumentDocId and remove any objects in the docReturnResult list that don't match the SharePointId's in the filterList.
This is what I tried last:
var trimResults = new DocumentSearchResult();
trimResults = docReturnResult.RemoveAll(x => x.DocumentDocId != filterList.Where(y => y.SharePointId));
but I get an error:
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.
Any help is much appreciated.
Try this, it should remove all documents from docReturnResult where match is not found in filterList
docReturnResult.RemoveAll(x => !filterList.Any(y => y.SharePointId == x.DocumentDocId));
Root cause of your error -
x.DocumentDocId != filterList.Where(y => y.SharePointId)
Right hand side will return IQuarable object and you are trying to compare it with DocumentDocId which will not work.
Edit
You don't need a new variable trmResults, as RemoveALL on docReturnResult will trim the same object, so you can just return docReturnResult
return docReturnResult.RemoveAll(x => !filterList.Any(y => y.SharePointId == x.DocumentDocId));

C# json deserialize object

I am new with C#, and so I don't know too much about it. I want to deserialize json object, but I am having some issues.
Thi is json object:
var json = "[{
"idSite":"1",
"visitorId":"a393fed00271f588",
"actionDetails":[{
"type":"action",
"url":"http:\/\/mysite.info\/test-24\/",
"customVariables":{
"1":{
"customVariablePageName1":"URL",
"customVariablePageValue1":"http:\/\/mysite.info\/p"
}
},
"timeSpent":"78",
}]
}]";
And I am trying to deserialize it on this way:
var visits = JsonConvert.DeserializeObject<VisitorDetails[]>(json);
public class VisitorDetails
{
public string idSite { get; set; }
public string visitorId { get; set; }
public List<ActionDetail> actionDetails { get; set; }
}
public class ActionDetail
{
public string type { get; set; }
public string url { get; set; }
public string timeSpent { get; set; }
public object customVariables { get; set; }
}
Everything is fine, except "customVariables" in "ActionDetails" it just set it to object with one value as string:
{
"1":{
"customVariablePageName1":"URL",
"customVariablePageValue1":"http:\/\/mysite.info\/p"
}
}
It doesn't deserialize it at all.
I need this deserialize so I can say:
foreach (var visit in Model.PiwikInfo)
{
#foreach (var action in visit.actionDetails)
{
#if (action.customVariables != null && action.customVariables.Any())
{
foreach (var cv in visit.customVariables.Where(cv => cv.HasProperty("customVariablePageName1")))
{
<span>URL: #cv.GetProperty("customVariablePageValue1")</span>
}
}
}
}
Well, this happens, because you have specified that the customVariables member is of type System.Object. So deserialization will result in assigning it the string value.
So lets try to mold it into a shape that better resembles the input JSON structure and your specific use of the deserialization result, in two steps, by changing the type declaration of the customVariables member variable, and inspecting its deserialized content after each change.
Make it a dictionary:
public Dictionary<string, object> customVariables { get; set; }
This will result in a dictionary that contains a single element with the key "1" and a single string value:
{
"customVariablePageName1": "URL",
"customVariablePageValue1": "http://mysite.info/p"
}
Make it a dictionary of dictionaries:
public Dictionary<string, Dictionary<string, string>> customVariables { get; set; }
And print its deserialized ouput like this:
var visits = JsonConvert.DeserializeObject<VisitorDetails[]>(json_string);
foreach (var visit in visits)
{
Console.WriteLine("Visitor: {0}", visit.visitorId);
foreach (var detail in visit.actionDetails)
{
Console.WriteLine(" Action: {0}", detail.type);
foreach (var cv in detail.customVariables.Where(x => x.Value.ContainsKey("customVariablePageName1")))
{
Console.WriteLine(" Custom variable #{0}", cv.Key);
Console.WriteLine(" Value: {0}", cv.Value["customVariablePageValue1"]);
}
}
}
Which resembles your view's foreach, and will produce the following output:
Visitor: a393fed00271f588
Action: action
Custom variable #1
Value: http://mysite.info/p
Since I can't still comment I will have to post this as an answer. have you tried using the built in function of C#?
See Here
Also, from what I gather, on the Documentation of that method it converts it converts the json into a system object.
Also, from the looks of it it seems like the customVariables segment is either an array or a broken object. I say that because it is missing the square brackets like in the previous declarations, making it look like:
...
"customVariables":[{
"1":[{
"customVariablePageName1":"URL",
"customVariablePageValue1":"http:\/\/mysite.info\/p"
}]
}],
...
Hope it helps.
try this structure
public class T1
{
public string customVariablePageName1 { get; set; }
public string customVariablePageValue1 { get; set; }
}
public class CustomVariables
{
public T1 t1 { get; set; }
}
public class ActionDetail
{
public string type { get; set; }
public string url { get; set; }
public CustomVariables customVariables { get; set; }
public string timeSpent { get; set; }
}
public class RootObject
{
public string idSite { get; set; }
public string visitorId { get; set; }
public List<ActionDetail> actionDetails { get; set; }
}

How to convert JSON Array to List<>?

This is my json and I need to access the values under each object in the attendance array:
{"name":" ","course":"","attendance":[{"name":"INTERNATIONAL FINANCE","type":"Theory","conducted":"55","present":"50"},{"name":"INDIAN CONSTITUTION","type":"Theory","conducted":"6","present":"6"}]}
Here is my code:
public class Att
{
public class Attendance
{
public string name { get; set; }
public string type { get; set; }
public string conducted { get; set; }
public string present { get; set; }
}
public Att(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject;
name = (string)jUser["name"];
course = (string)jUser["course"];
attender = jUser["attendance"].ToList<Attendance>;
}
public string name { get; set; }
public string course { get; set; }
public string email { get; set; }
//public Array attend { get; set; }
public List<Attendance> attender { get; set; }
}
It is the attender = jUser["attendance"].ToList<Attendance>; line that I have a problem with. It says,
Cannot convert method group ToList to non-delegate type. Did you intend to invoke this method?
How do I access those values?
You have a typo!
attendance vs attendence
And this should work
attender = jUser["attendance"].ToObject<List<Attendance>>();
You may find the running result at DotNetFiddle
You wanted to write:
attender = jUser["attendence"].ToList<Attendance>(); // notice the ()
About the Error:
When you dont put the parantheses there, C# assumes you want
to assign the function (delegate) ToList to the varaible attender, instead of
invoking it and assign its return value.

Storing and retrieving from lists with custom structures in

I'm having some trouble storing and retrieving items into a list<> with a custom structure.
My structure looks like this:
public class list_rss_parameters
{
public string this_string { get; set; }
public string title_start { get; set; }
public string title_end { get; set; }
public string description_start { get; set; }
public string description_end { get; set; }
public string link_start { get; set; }
public string link_end { get; set; }
public string publish_date_start { get; set; }
public string publish_date_end { get; set; }
public string author_start { get; set; }
public string author_end { get; set; }
}
My stored procedure looks like this (and note that the variable names are the same as the custom Key names) Is this ok?
//this is the last part of a custom method that returns a list
List<list_rss_parameters> list_rss_items = new List<list_rss_parameters>();
list_rss_items.Add(new list_rss_parameters()
{
this_string = this_string,
title_start = title_start,
title_end = title_end,
description_start = description_start,
description_end = description_end,
link_start = link_start,
link_end = link_end,
publish_date_start = publish_date_start,
publish_date_end = publish_date_end,
author_start = author_start,
author_end = author_end
});
return list_rss_items;
If the above two setups are correct, how do I pull items out of the List once I return it?
List<list_rss_parameters> list_rss_parameters = new List<list_rss_parameters>();
list_rss_parameters = f_discover_rss_parameters(rss);
show(list_rss_parameters.Count.ToString());
show(list_rss_parameters[0].ToString()); //does not show this_string
show(list_rss_parameters[this_string'] //does not show this_string
show(list_rss_parameters[0][this_string'];//does not show this_string
What am I doing wrong?
You want the this_string property of the first item in your list it seems:
show(list_rss_parameters[0].this_string);
Or show all of them:
foreach(var item in list_rss_parameters)
{
Console.WriteLine(item.this_string);
}
As a side note your property names don't match the PascalCase naming convention for properties in .NET - so this_string really should be ThisString.

Categories