How to Convert Style Text to C# Object Such as Class/Hashtable/Collection

How can I convert a class into Dictionarystring,string?

This is the recipe: 1 reflection, 1 LINQ-to-Objects!

 someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(someObject, null))

Since I published this answer I've checked that many people found it useful. I invite everyone looking for this simple solution to check another Q&A where I generalized it into an extension method: Mapping object to dictionary and vice versa

How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?

Json.NET does this...

string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

More examples: Serializing Collections with Json.NET

How to convert a string of key/value pairs to HashTable or Dictionary or?

I’m currently unable to test this, lacking a VB compiler, but the following solution should also work, and it has the advantage of not requiring an explicit loop. It uses the Linq method ToDictionary and two nested Split operations:

Dim s = "Name=Fred;Birthday=19-June-1906;ID=12345"
Dim d = s.Split(";"c).Select(Function (kvp) kvp.Split("="c)) _
.ToDictionary( _
Function (kvp) kvp(0), _
Function (kvp) kvp(1))

First, we split on the outer delimiter (i.e. the semi-colon). From the resulting array, we select by splitting again, this time on =. The resulting array of arrays is converted to a dictionary by specifying that the first item is to become the key and the second is to become the value (the identifier kvp stands for “key-value pair”).

Since I can’t check the exact VB syntax and the above may contain subtle errors, here is the equivalent C# code (tested for correctness):

var s = "Name=Fred;Birthday=19-June-1906;ID=12345";
var d = s.Split(';').Select(kvp => kvp.Split('='))
.ToDictionary(kvp => kvp[0], kvp => kvp[1]);

Converting PSCustomObject to Hashtable

If we assume your JSON has been converted to object $obj, you can do the following to output an array of hash tables.

$obj.Fields | Foreach-Object {
$hash = [ordered]@{}
$_.PsObject.Properties | Foreach-Object {
$hash[$_.Name] = $_.Value
}
$hash
}

Your output will need to be an array of hash tables because a single hash table cannot have duplicate key names.

C#: Printing all properties of an object

The ObjectDumper class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.

EDIT: I just realized, that the code for ObjectDumper is actually on your machine. Go to:

C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip

This will unzip to a folder called LinqSamples. In there, there's a project called ObjectDumper. Use that.

How to convert a DataTable to a string in C#?

You could use something like this:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
Dim sw As System.IO.StringWriter
Dim output As String

Console.WriteLine(label)

' Loop through each row in the table. '
For Each row As DataRow In table.Rows
sw = New System.IO.StringWriter
' Loop through each column. '
For Each col As DataColumn In table.Columns
' Output the value of each column's data.
sw.Write(row(col).ToString() & ", ")
Next
output = sw.ToString
' Trim off the trailing ", ", so the output looks correct. '
If output.Length > 2 Then
output = output.Substring(0, output.Length - 2)
End If
' Display the row in the console window. '
Console.WriteLine(output)
Next
Console.WriteLine()
End Sub

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'

Just make a class and deserialize it.

public class Print
{
public int PrintId { get; set; }
public string Header { get; set; }
public string TC { get; set; }
public string CompanyRef { get; set; }
}

Print printObj = JsonConvert.DeserializeObject<Print>(yourJson);
printObj.PrintId = //...

How to insert an item into a key/value pair object?

List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};

kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));

Using this code:

foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}

the expected output should be:

Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3

The same will work with a KeyValuePair or whatever other type you want to use..

Edit -

To lookup by the key, you can do the following:

var result = stringList.Where(s => s == "Lookup");

You could do this with a KeyValuePair by doing the following:

var result = kvpList.Where (kvp => kvp.Value == "Lookup");


Related Topics



Leave a reply



Submit