foreach over anonymous types - c#

using System;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace LearningJustCode
{
class Program
{
static void Main(string[] args)
{
Update();
}
static void Update()
{
var quote1 = new { Stock = "DELL", Quote = GetQuote("DELL") };
var quote2 = new { Stock = "MSFT", Quote = GetQuote("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = GetQuote("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}
Console.ReadKey();
}
static string GetQuote(string stock)
{
try
{
return InnerGetQuote(stock);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "N/A";
}
}
static string InnerGetQuote(string stock)
{
string url = #"http://www.webservicex.net/stockquote.asmx/GetQuote?symbol={0}";
var request = HttpWebRequest.Create(string.Format(url, stock));
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
return reader.ReadToEnd();
}
}
}
}
}
I am getting an squiggley over item;Variable 'item' is only assigned to. This code has been slightly modified from Paul Kimmel's book C# Unleashed by Sams.

Your array needs to be of the type of your stock quote.
Your stock quote is an anonymous type, so we need to define the array anonymously as well. This can be done cleanly as:
var quotes = new[]{ new { Stock = "DELL", Quote = "123" },
new { Stock = "MSFT", Quote = "123" },
new { Stock = "GOOG", Quote = "123" }};
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}

i guess the problem is in that line:
var quotes = new object[] { quote1, quote2, quote3 };
quotes is a object array, not an array of that anonymous type. the foreach also has just the object value. you could try to form the array within one line or within a lambda expression
A very dirty workaround is changing 'var' to 'dynamic'
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (dynamic item in quotes)
{
var r = item.Stock;
}
a cleaner solution is leaving out 'object', so the compiler can generate an anonymous typed array
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new [] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
var r = item.Stock;
}

Related

Adding an array property into an array of another object

I have this call that returns an array of treatments
var procedures = await client.GetProceduresAsync(clinicId);
I was trying to loop and insert all procedureIds (from the array) into an array property of the availableSlotsQuery
var availableSlotsQuery = new AvailableSlotsQuery();
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
ProcedureIds = new [] { procedure.Id},
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id
};
}
This is not working.
ProcedureIds is a string [] but after looping I only have one id in the ProcedureIds property
what am I doing wrong here?
with looping
var availableSlotsQuery = new AvailableSlotsQuery();
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id
};
var listOfProcedureIds = new List<string>();
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
listOfProcedureIds.Add(procedure.Id);
}
availableSlotsQuery.ProcedureIds = listOfProcedureIds.ToArray();
without looping
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id,
ProcedureIds = procedures.Select(x => x.Procedure.Id).ToArray()
};
as mentioned by all, you are creating a new object in your foreach statement
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
//as you can see here with the availableSlotQuery = new AvailableSlotQuery
availableSlotsQuery = new AvailableSlotsQuery
{
//properties
};
}

Write a text file with tab delimiter in .Net Core

Hi do you have any guides, work aid or step by step how to export to text with tab delimited. Im using Asp.Net Core 2.2 MVC EF. I want to export a list from my
table.. I want to have a button where the user click in this DownloadFile Action will trigger.
public object DownloadFile()
{
var payments = new List<BdoPE>
{
new BdoPE
{
DocDateInDoc = "01/01/2019",
DocType = "DZ",
CompanyCode = "3000",
PosDateInDoc = "01/01/2019",
FiscalPeriod = "01",
CurrentKey = "PHP",
RefDocNum = "Over-The-Counter",
DocHeadT = "BDO",
PosKeyInNextLine = "40",
AccMatNextLine = "11231131",
AmountDocCur = "0000000010050",
ValDate = "01/01/2019",
AssignNum = "EEA",
ItemText = "1000136212 ",
PosKeyInNextLine2 = "15",
AccMatNextLine2 = "0115027FF",
AmountDocCur2 = "0000000010050",
BaseDateDueCal = "01/01/2019",
ItemText2 = "1000136212"
},
};
// I want this part to let the user select where they want to save the text file.
using (var writer = new StreamWriter("path\\to\\file.txt")) // not static location like this one.
using (var csv = new CsvWriter(writer))
{
csv.WriteHeader<BdoPE>();
csv.WriteRecord(payments);
}
// where should i put the delimiter part?
return; // to what?
}
You should use this package https://joshclose.github.io/CsvHelper/
You can easily write a text file with tab delimiter.
using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
};
var configuration = new CsvHelper.Configuration.Configuration()
{
Delimiter = "\t"
};
using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, configuration))
{
csv.WriteRecords(records);
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}

C# Trying to split a string to get json object value

I am trying to split a string to get json object value - I have text values with numerous lines in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
What I would really like is to get them in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },
I know I can use JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. Is there a better way of doing this?
What I have so far:
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(#"c:\Data\temp\output.txt")) // file to write to
{
using (StreamReader reader = new StreamReader(#"c:\Data\temp\test.txt")) //file to read from
{
string line;
while (reader.ReadLine() != null)
{
line = reader.ReadLine();
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
}
}
}
}
static string[] JsonSplitString(string data)
{
return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
}
However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method.
You are calling reader.Readline() twice: once for the comparison and then again inside your loop. You are actually skipping every other line. And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. Try this instead:
line = reader.ReadLine();
while (line != null)
{
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;
namespace JsonExperiments
{
class Program
{
static void Main(string[] args)
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
// mockup JSON that would be returned from API
string sampleJson = "{\"results\":[" +
"{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
"]}";
// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);
// Process each employee
foreach (var result in results["results"])
{
// this can be a string or null
string employeeName = (string)result["employeename"];
// this can be a string or array, how can we tell which it is
JToken supervisor = result["employeesupervisor"];
string supervisorName = "";
if (supervisor is JValue)
{
supervisorName = (string)supervisor;
}
else if (supervisor is JArray)
{
// can pick one, or flatten array to a string
supervisorName = (string)((JArray)supervisor).First;
}
Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
}
}
}
}

looping through a C# collections

i have a class and method
public class Datas
{
public string Name { get; set; }
public int Value { get; set; }
}
public void Funnel()
{
string commandText = "select sc.stagename, count(cs.stages_id) as StageCount from currentstage cs inner join stagesconfig sc on cs.stages_id = sc.stages_id group by cs.stages_id,sc.stagename";
string constrings = WebConfigurationManager.ConnectionStrings["Data"].ToString();
SqlConnection myConn = new SqlConnection(constrings);
SqlCommand myComm = new SqlCommand(commandText, myConn);
myConn.Open();
List<Datas> fruitinfo = new List<Datas>();
SqlDataReader reader = myComm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
fruitinfo.Add(new Datas
{
Name = reader.GetValue(0).ToString(),
Value = Convert.ToInt32(reader.GetValue(1))
});
}
}
how do you loop through fruitinfo list saving it in form of an array.the array must be similar to this form.intended to replace the items in Data parenthesis with fruitinfo looped list
Data = new Data(new object[]
{
new object[] { "Website visits", 10000 },
new object[] { "Downloads", 5000 },
new object[] { "Requested price list", 2000 },
new object[] { "Invoice sent", 1000 },
new object[] { "Finalized", 500 }
}),
var myArray = fruitinfo.Select(x => new object[] { x.Name, x.Value }).ToArray();
And the use it with your Data-object.
Data = new Data(myArray);
var myArray = fruitinfo.Select(d => new object[] { d.Name, d.Value }).ToArray();
I am not too sure why you need to produce an array of anonymous objects, but you can use a dictionary.
private static void Funnel()
{
var datas = new List<Datas>
{
new Datas { Name = "Website visits", Value = 10000 },
new Datas { Name = "Downloads", Value = 5000 },
new Datas { Name = "Requested price list", Value = 2000 },
new Datas { Name = "Invoice sent", Value = 1000 },
new Datas { Name = "Finalized", Value = 500 }
};
var data = datas.ToDictionary(datas1 => datas1.Name, datas1 => datas1.Value);
foreach (var item in data)
{
Console.WriteLine(string.Format("{0}, {1}",item.Key, item.Value));
}
var arry = data.ToArray();
foreach (var item in arry)
{
Console.WriteLine(string.Format("{0}, {1}", item.Key, item.Value));
}
}

Alternate foreach output

I have this code which grabs the specified text from a webpage:
static void Main(string[] args)
{
using (var client = new WebClient())
{
var pageContent = client.DownloadString("http://www.modern-railways.com");
var regexTitle = new Regex(#"<span class='articleTitle'>(.+?)</span>");
var regexDate = new Regex(#"class='summaryText' data-ajax='false'>(.+?)</a></p><div");
foreach (Match title in regexTitle.Matches(pageContent))
{
var articleTitle = title.Groups[1].Value;
Console.WriteLine(articleTitle);
}
foreach (Match date in regexDate.Matches(pageContent))
{
var articleDate = date.Groups[1].Value;
Console.WriteLine(articleDate);
}
Console.ReadLine();
}
}
As it is now it prints all the articleTitle first and then all the articleDate. How can I get out 1st line ArticleTitle, second line articleDate and so on?
You can use LINQ and Zip method:
var titles = regexTitles.Matches(pageContent).Cast<Match>();
var dates = regexDate.Matches(pageContent).Cast<Match>();
var source = titles.Zip(dates, (t, d) => new { Title = t, Date = d })
foreach (var item in source)
{
var articleTitle = item.Title.Groups[1].Value;
var articleDate = item.Date.Groups[1].Value;
Console.WriteLine(articleTitle);
Console.WriteLine(articleDate);
}

Categories