How to split string and assign as column and row in table - c#

I have a input strings example
str1 = ""Type":"#Microsoft.Azure","Email":"abc#tmail.com","DisplayName":"abc","Dpt":"home"";
str2 = ""Type":"#Microsoft.Azure","Email":"xyz#tmail.com","DisplayName":"xyz","Dpt":"home"";
In compileable form it looks like this:
string str = #"""Type"":""#Microsoft.Azure"",""Email"":""abc#tmail.com"",""DisplayName"":""abc"",""Dpt"":""home""";
Can i split on "," delimiter and assign left to ":" as columns and right to ":" as rows in table.
Example:
"Type" "Email" "DisplayName" "Dpt"
"#Microsoft.Azure" "abc#tmail.com" "abc" "home"
"#Microsoft.Azure" "xyz#tmail.com" "xyz" "home"
i tried something like this
string str = ' "name":"abd","":""m"":"" ';
string[] strS1 = str.split(',');
foreach(string S1 in strS1){
string[] strS2 = str.split(':');
foreach(string S2 in strS2){
console.write(s2)
}
}

You can try something like this : Demo
The Json Way.
You assume it's a Json.
Join the line with },{. Add a Starting [{ and Ending }]. Bim, You are ready to go.
Deserilise to you custom type : I ignored Type property here
JsonConvert.DeserializeObject<List<CsvItem>>(myJSON);
public class CsvItem
{
public string Email { get; set; }
public string DisplayName { get; set; }
public string Dpt { get; set; }
}
Your parsing way: String Split.
After the S1.Split(':'), you end up with a small array the first value is the property name the second the value.
Trim the ", compare and assign.
if (strS2[0].Trim('"') == "Email") temp.Email = strS2[1].Trim('"');
if (strS2[0].Trim('"') == "DisplayName") temp.DisplayName = strS2[1].Trim('"');
if (strS2[0].Trim('"') == "Dpt") temp.Dpt = strS2[1].Trim('"');
Same thing in LinQ:
At this point it's not faster, easier to maintain, not even easier to read. It's just compact
lines
.Select(x => x.Split(','))
.Select(x =>
new CsvItem
{
Email = x[1].Split(':')[1].Trim('"'),
DisplayName = x[2].Split(':')[1].Trim('"'),
Dpt = x[3].Split(':')[1].Trim('"')
})
What's left?
Regex like : "(\w+)":"(.+?)", could easy replace the split. With a more detailed regex you can catch only the value you need.
What solution in the end?
Depending on the quality of the file. If it's human generated and can containt error.
You way to handle the error: Do you reject the whole file in case of error? Do you return only the list of valid data? etc.
I will choose either Solution #1 or #2. #1 for sometime broken file. #2 for meticulous error handleing and debugging.
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string inputCSV = #"""Type"":""#Microsoft.Azure"",""Email"":""abc#tmail.com"",""DisplayName"":""abc"",""Dpt"":""home""
""Type"":""#Microsoft.Azure"",""Email"":""xyz#tmail.com"",""DisplayName"":""xyz"",""Dpt"":""home""";
// ReadAllLines mock
string[] lines = inputCSV.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
{ // The Json Way
var bringJsonBack = "[\n{" + string.Join("},\n{", lines) + "}\n]";
var results = JsonConvert.DeserializeObject<List<CsvItem>>(bringJsonBack);
results.Dump();
}
{ // Your working way
var results = new List<CsvItem>();
foreach (var line in lines)
{
var temp = new CsvItem();
string[] strS1 = line.Split(',');
foreach (string S1 in strS1)
{
string[] strS2 = S1.Split(':');
// You have a part Before the : and one after we just string check to know what property we re on.
if (strS2[0].Trim('"') == "Email")
{
temp.Email = strS2[1].Trim('"');
}
if (strS2[0].Trim('"') == "DisplayName")
{
temp.DisplayName = strS2[1].Trim('"');
}
if (strS2[0].Trim('"') == "Dpt")
{
temp.Dpt = strS2[1].Trim('"');
}
}
results.Add(temp);
}
results.Dump();
}
{ // LinQ Version of your algo.
var results = lines
.Select(x => x.Split(','))
.Select(x =>
new CsvItem
{
Email = x[1].Split(':')[1].Trim('"'),
DisplayName = x[2].Split(':')[1].Trim('"'),
Dpt = x[3].Split(':')[1].Trim('"')
})
.ToList();
results.Dump();
}
}
public class CsvItem
{
public string Email { get; set; }
public string DisplayName { get; set; }
public string Dpt { get; set; }
}
}

Your original string looks suspiciously like it was extracted from a JSON response. You should just deserialize the original JSON response directly into a DataTable with Newtonsoft.Json, ala:
//Install-Package Newtonsoft.Json
using Newtonsoft.Json;
using System.Data;
namespace Split_string_and_assign_as_table
{
class Program
{
static void Main(string[] args)
{
string json = #"[
{
""Type"": ""#Microsoft.Azure"",
""Email"": ""abc#tmail.com"",
""DisplayName"": ""abc"",
""Dpt"": ""home""
},
{
""Type"": ""#Microsoft.Azure"",
""Email"": ""xyz#tmail.com"",
""DisplayName"": ""xyz"",
""Dpt"": ""home""
}
]";
var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
}
}
}

Related

How to properly access object's List<> value in C#?

I am trying to get the object value but I don't know how to do it. I'm new to C# and its giving me syntax error. I want to print it separately via the method "PrintSample" How can I just concatenate or append the whatData variable . Thank you.
PrintSample(getData, "name");
PrintSample(getData, "phone");
PrintSample(getData, "address");
//Reading the CSV file and put it in the object
string[] lines = File.ReadAllLines("sampleData.csv");
var list = new List<Sample>();
foreach (var line in lines)
{
var values = line.Split(',');
var sampleData = new Sample()
{
name = values[0],
phone = values[1],
address = values[2]
};
list.Add(sampleData);
}
public class Sample
{
public string name { get; set; }
public string phone { get; set; }
public string adress { get; set; }
}
//Method to call to print the Data
private static void PrintSample(Sample getData, string whatData)
{
//THis is where I'm having error, how can I just append the whatData to the x.?
Console.WriteLine( $"{getData. + whatData}");
}
In C# it's not possible to dynamically evaluate expression like
$"{getData. + whatData}"
As opposed to languages like JavaScript.
I'd suggest to use rather switch expression or Dictionary<string, string>
public void PrintData(Sample sample, string whatData)
{
var data = whatData switch
{
"name" => sample.name,
"phone" => sample.phone,
"address" => sample.address
_ => throw new ArgumentOutOfRangeException(nameof(whatData)),
};
Console.WriteLine(data);
}
I'm not sure what you are trying to achieve. Perhaps this will help you:
private static void PrintSample(Sample getData, string whatData)
{
var property = getData.GetType().GetProperty(whatData);
string value = (string)property?.GetValue(getData) ?? "";
Console.WriteLine($"{value}");
}
What PO really needs is
private static void PrintSamples(List<Sample> samples)
{
foreach (var sample in samples)
Console.WriteLine($"name : {sample.name} phone: {sample.phone} address: {sample.address} ");
}
and code
var list = new List<Sample>();
foreach (var line in lines)
{
......
}
PrintSamples(list);
it is radicolous to use
PrintSample(getData, "name");
instead of just
PrintSample(getData.name)
You can do this using reflection. However, it's known to be relatively slow.
public static void PrintSample(object getData, string whatData)
{
Console.WriteLine( $"{getData.GetType().GetProperty(whatData).GetValue(getData, null)}");
}

How to iterate through JObject Properties via Foreach/LINQ

I have an established JObject object. Trying to loop through it to acquire a Key/value based on anothers Key/value (example of json below with code currently stuck on)
For a tad more detail - looking to loop through "value", get the "KeyID" based on "MailState"
definitely feel like I am missing the step of filtering by MailState/ColName apparently - I have searched through threads a bunch but if someone knows of one that answered this that i was unable to find i will happily pull this down/reference it
// JSON DATA
{
"odata.metadata": "https://..com/odata/$metadata#JCJMCDXes",
"value": [
{
"KeyID": "10379",
"MailCity": "Chicago",
"MailState": "IL"
},
{
"KeyID": "9846",
"MailCity": "Chicago",
"MailState": "IL"
},
{
"KeyID": "2234",
"MailCity": "Madison",
"MailState": "WI"
}]
}
// Current code example
// class in play
public class datastorage
{
public string ID { get; set; }
public string Col { get; set; }
}
public class listData
{
public string ColName {get;set;}
}
// getVPData is a string response from a call to an API
getVPData.Replace(System.Environment.NewLine, "");
JObject jobj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(getVPData);
List<datastorage> data = new List<datastorage>();
// Loop
foreach(var r in listData) // has distinct State abeviations so only 1 occurence
{
foreach (var j in jobj) // This the right path?
{
//add KeyID into ID
data.add(new datastorage
{
ID = ,//add KeyID into ID
Col = r.ColName
});
}
}
You can use Newtonsoft.Json library to parse and loop to the items of value
here is a sample code:
dynamic json = JsonConvert.DeserializeObject(getVPData);
foreach (dynamic item in json["value"])
{
//you can access the fields inside value.
var KeyID = item["KeyID"];
var MailCity = item["MailCity"];
var MailState = item["MailState"];
//just for showing...
Console.WriteLine("KeyID:{0}, MailCity:{1}, MailState:{2}", KeyID, MailCity, MailState);
}
Let me know if the snippet works.
Straightforward ways are:
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp7
{
internal class Program
{
private static void Main(string[] args)
{
var mailStates = new[] {"IL", "WI"};
var jObject = (JObject) JsonConvert.DeserializeObject(json);
var values = (JArray) jObject["value"];
// 1st way
foreach (var mailState in mailStates)
{
var key = values
.Where(v => mailState == v.SelectToken("MailState").Value<string>())
.Select(v => v.Value<string>("KeyID"))
.FirstOrDefault();
Console.WriteLine($"1st case: {mailState} - {key}");
}
/* 2nd way based on JSONPath
* api: https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm
* dox: https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html
* tester: https://jsonpath.curiousconcept.com/
*/
foreach (var mailState in mailStates)
{
var key = values.SelectTokens($"$[?(#.MailState == '{mailState}')].KeyID")
.Select(v => v.ToString())
.FirstOrDefault();
Console.WriteLine($"2nd case: {mailState} - {key}");
}
Console.ReadKey();
}
private static string json = #"
{
""odata.metadata"": ""https://cdxapiclient.palmercg.com/odata/$metadata#JCJMCDXes"",
""value"": [
{
""KeyID"": ""10379"",
""MailCity"": ""Chicago"",
""MailState"": ""IL""
},
{
""KeyID"": ""9846"",
""MailCity"": ""Chicago"",
""MailState"": ""IL""
},
{
""KeyID"": ""2234"",
""MailCity"": ""Madison"",
""MailState"": ""WI""
}]
}";
}
}

NewtonSoft json parsing

Can somebody help me to parse the json and get the details.
Lets say i have Top2 input parameter as Police and i want to know the respective Top3 and in that Top3 array i need to check whether Test1Child value is there or not.
I am using newtonsoft json + c# and so far i can get till DeviceTypes using below code
var json = File.ReadAllText(jsonFile); // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray MappingArray =(JArray)jObject["Top1"];
string strTop1 = ObjZone.Top1.ToString();
string strTop2 = ObjZone.Top2.ToString();
var JToken = MappingArray.Where(obj => obj["Top2"].Value<string>() == strTop2).ToList();
//Json
{
"Top1": [
{
"Top2": "Test1",
"Top3": [
"Test1Child"
]
},
{
"Top2": "Test2",
"Top3": [
"Test2Child"
]
}
]
}
I'd use http://json2csharp.com/ (or any other json to c# parser) and then use C# objects (it's just easier for me)
This would look like that for this case:
namespace jsonTests
{
public class DeviceTypeWithResponseTypeMapper
{
public string DeviceType { get; set; }
public List<string> ResponseTypes { get; set; }
}
public class RootObject
{
public List<DeviceTypeWithResponseTypeMapper> DeviceTypeWithResponseTypeMapper { get; set; }
}
}
and the use it like that in code:
var rootob = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(str);
var thoseThatHaveNotUsed = rootob.DeviceTypeWithResponseTypeMapper.Where(dtwrtm =>
dtwrtm.ResponseTypes.Any(rt => rt == "NotUsed"));
foreach (var one in thoseThatHaveNotUsed)
{
Console.WriteLine(one.DeviceType);
}
this code lists all the Device types that have "NotUsed" among the responses.
version 2 (extending your code) would look like that, i believe:
static void Main(string[] args)
{
var json = str; // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray ZoneMappingArray = (JArray)jObject["DeviceTypeWithResponseTypeMapper"];
string strDeviceType = "Police";
string strResponseType = "NotUsed";
var JToken = ZoneMappingArray.Where(obj => obj["DeviceType"].Value<string>() == strDeviceType).ToList();
var isrespTypeThere = JToken[0].Last().Values().Any(x => x.Value<string>() == strResponseType);
Console.WriteLine($"Does {strDeviceType} have response type with value {strResponseType}? {yesorno(isrespTypeThere)}");
}
private static object yesorno(bool isrespTypeThere)
{
if (isrespTypeThere)
{
return "yes!";
}
else
{
return "no :(";
}
}
result:
and if you'd like to list all devices that have response type equal to wanted you can use this code:
var allWithResponseType = ZoneMappingArray.Where(jt => jt.Last().Values().Any(x => x.Value<string>() == strResponseType));
foreach (var item in allWithResponseType)
{
Console.WriteLine(item["DeviceType"].Value<string>());
}

Elastic Search to search for words that starts with phrase

I'm trying to create a search function for my website using Elastic Search and NEST. You can see my code below and I get results if I search for complete (and almost comlete) words.
Ie, if I search for "Buttermilk" or "Buttermil" I get a hit on my document containing the word "Buttermilk".
However, what I try to accomplish is if I search for "Butter", I should have a result with all three documents which have words that starts with "Butter". I thought this was solved by using FuzzyLikeThis?
Can anyone see what I'm doing wrong and point me in the right direction?
I created a console-app and the complete code you can see here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nest;
using Newtonsoft.Json;
namespace ElasticSearchTest
{
class Program
{
static void Main(string[] args)
{
var indexSettings = new IndexSettings();
indexSettings.Analysis.Analyzers["text-en"] = new SnowballAnalyzer { Language = "English" };
ElasticClient.CreateIndex("elastictesting", indexSettings);
var testItem1 = new TestItem {
Id = 1,
Name = "Buttermilk"
};
ElasticClient.Index(testItem1, "elastictesting", "TestItem", testItem1.Id);
var testItem2 = new TestItem {
Id = 2,
Name = "Buttercream"
};
ElasticClient.Index(testItem2, "elastictesting", "TestItem", testItem2.Id);
var testItem3 = new TestItem {
Id = 3,
Name = "Butternut"
};
ElasticClient.Index(testItem3, "elastictesting", "TestItem", testItem3.Id);
Console.WriteLine("Write search phrase:");
var searchPhrase = Console.ReadLine();
var searchResults = Search(searchPhrase);
Console.WriteLine("Number of search results: " + searchResults.Count());
foreach (var item in searchResults) {
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
private static List<TestItem> Search(string searchPhrase)
{
var query = BuildQuery(searchPhrase);
var result = ElasticClient
.Search(query)
.Documents
.Select(d => d)
.Distinct()
.ToList();
return result;
}
public static ElasticClient ElasticClient
{
get
{
var localhost = new Uri("http://localhost:9200");
var setting = new ConnectionSettings(localhost);
setting.SetDefaultIndex("elastictesting");
return new ElasticClient(setting);
}
}
private static SearchDescriptor<TestItem> BuildQuery(string searchPhrase)
{
var querifiedKeywords = string.Join(" AND ", searchPhrase.Split(' '));
var filters = new BaseFilter[1];
filters[0] = Filter<TestItem>.Bool(b => b.Should(m => m.Query(q =>
q.FuzzyLikeThis(flt =>
flt.OnFields(new[] {
"name"
}).LikeText(querifiedKeywords)
.PrefixLength(2)
.MaxQueryTerms(1)
.Boost(2))
)));
var searchDescriptor = new SearchDescriptor<TestItem>()
.Filter(f => f.Bool(b => b.Must(filters)))
.Index("elastictesting")
.Type("TestItem")
.Size(500);
var jsons = JsonConvert.SerializeObject(searchDescriptor, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return searchDescriptor;
}
}
class TestItem {
public int Id { get; set; }
[ElasticProperty(Analyzer = "text-en", Index = FieldIndexOption.analyzed)]
public string Name { get; set; }
}
}
Edited 2014-04-01 11:18
Well, I ended up using MultiMatch and QueryString, so this it how my code looks now. Hope it mey help anyone in the furure. Also, I added a Description property to my TestItem to illustrate multimatch.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nest;
using Newtonsoft.Json;
namespace ElasticSearchTest
{
class Program
{
static void Main(string[] args)
{
var indexSettings = new IndexSettings();
ElasticClient.CreateIndex("elastictesting", indexSettings);
var testItem1 = new TestItem {
Id = 1,
Name = "Buttermilk",
Description = "butter with milk"
};
ElasticClient.Index(testItem1, "elastictesting", "TestItem", testItem1.Id);
var testItem2 = new TestItem {
Id = 2,
Name = "Buttercream",
Description = "Butter with cream"
};
ElasticClient.Index(testItem2, "elastictesting", "TestItem", testItem2.Id);
var testItem3 = new TestItem {
Id = 3,
Name = "Butternut",
Description = "Butter with nut"
};
ElasticClient.Index(testItem3, "elastictesting", "TestItem", testItem3.Id);
Console.WriteLine("Write search phrase:");
var searchPhrase = Console.ReadLine();
var searchResults = Search(searchPhrase);
Console.WriteLine("Number of search results: " + searchResults.Count());
foreach (var item in searchResults) {
Console.WriteLine(item.Name);
Console.WriteLine(item.Description);
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
private static List<TestItem> Search(string searchPhrase)
{
var query = BuildQuery(searchPhrase);
var result = ElasticClient
.Search(query)
.Documents
.Select(d => d)
.Distinct()
.ToList();
return result;
}
public static ElasticClient ElasticClient
{
get
{
var localhost = new Uri("http://localhost:9200");
var setting = new ConnectionSettings(localhost);
setting.SetDefaultIndex("elastictesting");
return new ElasticClient(setting);
}
}
private static SearchDescriptor<TestItem> BuildQuery(string searchPhrase)
{
var searchDescriptor = new SearchDescriptor<TestItem>()
.Query(q => q
.MultiMatch(m =>
m.OnFields(new[] {
"name",
"description"
}).QueryString(searchPhrase).Type(TextQueryType.PHRASE_PREFIX)
)
)
.Index("elastictesting")
.Type("TestItem")
.Size(500);
var jsons = JsonConvert.SerializeObject(searchDescriptor, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return searchDescriptor;
}
}
class TestItem {
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Instead of using FuzzyLikequery.. use prefix query its more fast and accurate..!
for more information refer
curl -XPOST "http://localhost:9200/try/indextype/_search" -d'
{
"query": {
"prefix": {
"field": {
"value": "Butter"
}
}
}
}'
create above query in NEST and try again..!
This has nothing to do with FuzzyLikeThis.
You can use prefixquery as suggested by #BlackPOP out of the box.
You could also opt for using EdgeNGrams, this will tokenize your input on index-time. The result faster performance as compared to prefixquery, offset against increased index size.
One thing to keep in mind is that prefixquery only works on non-analyzed fields, so if you want to do any anaylzing at indexing-time, you're probably better off using EdgeNGrams.
Please read up on anaylzers etc, if you don't know what they are.
Some refs:
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis-analyzers.html
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html
See How can I do a prefix search in ElasticSearch in addition to a generic query string? for a similar question.

Convert array to multidimensional array in C#

I'm quite new with C#. I have a function which gives me the results in an array like this
[0] => value
[1] => value
[2] => value
[3] => value
[4] => value
But in my case, [0] [1] [2] need to be together, and I show them in a table in PHP.
This is my function:
public List<string> ReadOpenCalls(int relation)
{
IQAssemblyResolver.Initialize(#"C:\Program Files\.....");
IQSDK IQSDK = new IQSDK();
string loginTekst = IQSDK.Login("Administrator", "..", "..").GetResult();
SDKRecordset inboundSet = IQSDK.CreateRecordset("R_ACTIONSCOPE", "CODE, DESCRIPTION, DATECREATED", "FK_RELATION = " + relation, "");
var messages = new List<string>();
if (inboundSet != null && inboundSet.RecordCount > 0)
{
inboundSet.MoveFirst();
do
{
string code = inboundSet.Fields["CODE"].Value.ToString();
string desc = inboundSet.Fields["DESCRIPTION"].Value.ToString();
string date = inboundSet.Fields["DATECREATED"].Value.ToString();
messages.Add( code);
messages.Add( desc);
messages.Add( date);
inboundSet.MoveNext();
}
while (!inboundSet.EOF);
return messages;
}
messages.Add("Error niet gelukt");
return messages;// null;
}
I want the output to be something like this:
[0] => [0] => "desc"
[1] => "code"
[2] => "date"
So that I can output this in a nice way in my table in PHP.
A very quick fix:
var messages = new List<string[]>();
...
messages.Add( new string[] { code, desc, date});
But it also depends on what is easy to work with in PHP.
A better solution, probably, is to write a small class:
class MyMessage
{
public string Code { get; set; }
public string Desc { get; set; }
public string Date { get; set; }
}
And of course you'd have to change the method into one of:
public List<string[]> ReadOpenCalls(int relation) ...
public List<MyClass> ReadOpenCalls(int relation) ...
and that change also needs to be made in the ServiceContract etc.
PHP induces bad practices and a horrible understanding of data structures. Please do not try to pattern anything after whatever you saw or did in PHP. In particular, using array indices as a substitute for proper members.
Have you considered writing a class that has three fields to describe a message?
Ideally you want to change the existing function, however using System.Linq you could alter your results after you've generated them.
var messages = ReadOpenCalls(relation);
var new messages = messages.Select((a,i) => new {index = i / 3, value = a})
.GroupBy (y => y.index, y => y.value)
.Select(g => g.ToList())
.ToList();
However you would be far better altering your function
either add the list directly
public List<List<string>> ReadOpenCalls(int relation)
{
IQAssemblyResolver.Initialize(#"C:\Program Files\.....");
IQSDK IQSDK = new IQSDK();
string loginTekst = IQSDK.Login("Administrator", "..", "..").GetResult();
SDKRecordset inboundSet = IQSDK.CreateRecordset("R_ACTIONSCOPE", "CODE, DESCRIPTION, DATECREATED", "FK_RELATION = " + relation, "");
var messages = new List<List<string>>();
if (inboundSet != null && inboundSet.RecordCount > 0)
{
inboundSet.MoveFirst();
do
{
string code = inboundSet.Fields["CODE"].Value.ToString();
string desc = inboundSet.Fields["DESCRIPTION"].Value.ToString();
string date = inboundSet.Fields["DATECREATED"].Value.ToString();
messages.Add(new List<string> { code, desc, date});
inboundSet.MoveNext();
}
while (!inboundSet.EOF);
return messages;
}
messages.Add("Error niet gelukt");
return messages;// null;
}
or make a class to hold the values and return a list of the class
UPDATE - OP has stated this is in a webservice so I've added the DataContract and DataMember attributes. You will need to make sure the project references System.Runtime.Serialization
using System.Runtime.Serialization;
[DataContract]
public class Class {
public Class(string code, string desc, string date) {
this.code = code;
this.desc = desc;
this.date = date;
}
[DataMember]
public string Code { get;set; }
[DataMember]
public string Desc { get;set; }
[DataMember]
public string Date { get;set; }
}
And then your altered function
public List<Call> ReadOpenCalls(int relation)
{
IQAssemblyResolver.Initialize(#"C:\Program Files\.....");
IQSDK IQSDK = new IQSDK();
string loginTekst = IQSDK.Login("Administrator", "..", "..").GetResult();
SDKRecordset inboundSet = IQSDK.CreateRecordset("R_ACTIONSCOPE", "CODE, DESCRIPTION, DATECREATED", "FK_RELATION = " + relation, "");
var messages = new List<Call>();
if (inboundSet != null && inboundSet.RecordCount > 0)
{
inboundSet.MoveFirst();
do
{
string code = inboundSet.Fields["CODE"].Value.ToString();
string desc = inboundSet.Fields["DESCRIPTION"].Value.ToString();
string date = inboundSet.Fields["DATECREATED"].Value.ToString();
messages.Add( new Call(code,desc, date));
inboundSet.MoveNext();
}
while (!inboundSet.EOF);
return messages;
}
messages.Add("Error niet gelukt");
return messages;// null;
}
Try this,
Change
public List<string> ReadOpenCalls(int relation)
to
public List<List<string>> ReadOpenCalls(int relation)
Change
var messages = new List<string>();
to
var messages = new List<List<string>>();
And change
messages.Add( code);
messages.Add( desc);
messages.Add( date);
to
List<string> list = new List<string>();
list.Add( code);
list.Add(desc);
list.Add(date);
messages.Add(list);
Change function return value to string[][] and return the jagged array however you like.

Categories

Resources