Alternate foreach output - c#

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);
}

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
};
}

Get Connected Elements in Autodesk Inventor via API

We have Autodesk Inventor and created a C# Addon.
In this we loop through all Objects like this:
foreach (CurrencyAPIv2.IAssetInstance s in objects)
{
var c = s.NativeObject as ComponentOccurrence;
}
How can we get the connected Object of an Object (the one which is snapped to it). And also the Info to which connector it is connected (snapped)
Michael Navara:
Can you be more specific? CurrencyAPIv2.IAssetInstance is not a member of Inventor API
using CurrencyAPIv2 = Autodesk.Factory.PublicAPI.Currency.v2;
We solved it with the XML-files which can also be watched in AttributeHelper:
void LoadConnectors(Document document, List<ConnectionElement> connections, List<ConnectedComponent> components)
{
var am = document.AttributeManager;
var d = new Dictionary<string, string>();
var entities = am.FindObjects("*", "*");
foreach (var e in entities)
{
try
{
dynamic o = e;
foreach (AttributeSet attrS in o.AttributeSets)
{
foreach (Inventor.Attribute a in attrS)
{
d.Add(o.Name, a.Value as string);
}
}
}
catch(Exception)
{ }
}
foreach (var element in d)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(element.Value);
var connectionNodes = xmlDoc.SelectNodes("//ObjectData[#Type='42']");
var componentNodes = xmlDoc.SelectNodes("//ObjectData[#Type='38']");
// Verbindungen
if (connectionNodes.Count > 0)
{
var link1Node = xmlDoc.SelectSingleNode("//ObjectData/Link1") as XmlElement;
var link2Node = xmlDoc.SelectSingleNode("//ObjectData/Link2") as XmlElement;
var connection = new ConnectionElement();
connection.Name = element.Key;
connection.Link1 = link1Node.GetAttribute("VAL");
connection.Link2 = link2Node.GetAttribute("VAL");
connections.Add(connection);
}
// Komponenten
else if (componentNodes.Count > 0)
{
var componentConnectorNodes = xmlDoc.SelectNodes("//ObjectData/Connector");
var componentConnectors = new List<ComponentConnector>();
foreach (XmlNode cc in componentConnectorNodes)
{
var idNode = cc.SelectSingleNode("Id") as XmlElement;
var displayNameNode = cc.SelectSingleNode("DisplayName") as XmlElement;
var connector = new ComponentConnector();
connector.DisplayName = displayNameNode.GetAttribute("VAL");
connector.Id = idNode.GetAttribute("VAL");
componentConnectors.Add(connector);
}
if (components.FirstOrDefault(x => x.Name == element.Key) != null)
{
components.FirstOrDefault(x => x.Name == element.Key).Connectors.AddRange(componentConnectors);
}
else
{
var component = new ConnectedComponent();
component.Name = element.Key;
component.Connectors = new List<ComponentConnector>();
component.Connectors.AddRange(componentConnectors);
components.Add(component);
}
}
}
}

How to convert table format to string programmatically

Good day all,
would like request to how to convert table format to string
eg:
Material Control August
Development September
Planning August
HR September
to
September: Development, HR
August : Material Control, Planning
List<String> returnvalueStringMonth = new List<String>();
List<String> returnvalueStringDept = new List<String>();
foreach (DataRow dr in dsSeries.Tables[0].Rows)
{
string newmanout = dr["MonthNames"].ToString();
returnvalueStringMonth.Add(newmanout);
string Departs = dr["Depart"].ToString();
returnvalueStringMonth.Add(Departs);
//var DDLName = dr["Depart"];
//Label dynamicLabel = new Label();
//dynamicLabel.Text = DDLName.ToString() + ",";
//div1.Controls.Add(dynamicLabel);
//var sumPlus = Convert.ToDouble(newmanout) +",";
}
List<string> b = new List<string>();
b.AddRange(returnvalueStringMonth.Distinct());
for (int cs = 0; cs < b.Count; cs++)
{
//Panel aspPanel = new Panel();
Label dynamicLabel = new Label();
dynamicLabel.Text = b[cs].ToString()+":" + "<br/>";
div1.Controls.Add(dynamicLabel);
}
I able achive until month only, then i realize made mistake.
So, please advise how to achive this.
The code below will fill a list of strings with your desired output. You can change the second loop to do what you want.
var monthList = new Dictionary<String, List<String>>();
foreach (DataRow dr in dsSeries.Tables[0].Rows)
{
var key = dr["MonthName"].ToString();
var value = dr["Department"].ToString();
if (!monthList.ContainsKey(key))
{
monthList.Add(key, new List<string>());
}
monthList[key].Add(value);
}
List<string> b = new List<String>();
foreach (var month in monthList.Keys)
{
b.Add(month + ": " + String.Join(", ", monthList[month])");
}
If you would rather use LINQ, you can do this instead:
var q = from row in dsSeries.Tables[0].AsEnumerable()
group row by row["Month"] into qGrouped
orderby qGrouped.Key
select String.Format("{0}: {1}", qGrouped.Key,
String.Join(", ", Array.ConvertAll(qGrouped.ToArray(), r => r["Department"])));
var b = q.ToList();
public class TestClass
{
public string S1 { get; set; }
public string S2 { get; set; }
}
[TestMethod]
public void MyTest()
{
// Material Control August
//Development September
//Planning August
//HR September
var list = new List<TestClass>
{
new TestClass {S1 = "Material Control", S2 = "August"},
new TestClass {S1 = "Development", S2 = "September"},
new TestClass {S1 = "Planning", S2 = "August"},
new TestClass {S1 = "HR", S2 = "September"}
};
var listGroupByMonth = list.GroupBy(l => l.S2);
foreach (var lstByMonth in listGroupByMonth)
{
var key = lstByMonth.Key;
var finalValue = string.Join(", ", lstByMonth.ToList().Select(lbm => lbm.S1));
}
}

How i can add Couchbase Documents in a list?

I'm experimenting with Couchbase + Xamarin.Forms trying to do a simple search, showing the results in a ListView but I've stuck. :(
Someone know how to add the rows/documents of a query in a list?
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
emit (new object[] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
// visitorQuery.EndKey = new List<object> {word, new Dictionary<string, object>()};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
// visitorList.Add(visitor.Document); <-- Error.
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I get the error messages:
Error CS1501: No overload for method Add' takes2' arguments
(CS1501) (Demo_Couchbase.Droid) Error CS1502: The best overloaded
method match for
System.Collections.Generic.List<Demo_Couchbase.Visitor>.Add(Demo_Couchbase.Visitor)'
has some invalid arguments (CS1502) (RegistroAgil_Couchbase.Droid)
Error CS1503: Argument#1' cannot convert Couchbase.Lite.Document'
expression to typeDemo_Couchbase.Visitor' (CS1503)
(Demo_Couchbase.Droid)
Thank you in advance for any help you can provide.
There is problem in your mapping part. You can directly cast documents on GetView.
You can try bellow code.
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView<Visitor>("ByName","ByName");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
visitorList.Add(visitor.Document);
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I don't know if this is the most elegant solution though but my code works fine now.
Visitor ToRecord(Document d) {
var props = d.Properties;
return new Visitor {
Id = props["_id"].ToString(),
FirstName = (string)props["first_name"],
LastName = (string)props["last_name"],
Occupation = (string)props["occupation"],
Company = (string)props["company"],
Email = (string)props["email"],
Phone = (string)props["phone"],
Birthday = (string)props["birthday"],
LastVisit = (string)props["last_visit"],
LocalImagePath = (string)props["local_image_path"],
Type = (string)props["type"],
CreatedAt = (string)props["created_at"],
UpdatedAt = (string)props["updated_at"],
DeletedAt = (string)props["deleted_at"]
};
}
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
if ((doc.ContainsKey("type") && doc["type"].ToString() == "visitor") && (doc.ContainsKey("deleted_at") && doc["deleted_at"] == null))
emit (new [] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = word;
visitorQuery.Limit = 50;
var rows = visitorQuery.Run();
var visitorList = new List<Visitor> ();
for (int i = 0; i < rows.Count (); i++) {
var row = rows.GetRow (i);
var name = row.Document.GetProperty ("first_name").ToString ().ToLower () + " " + row.Document.GetProperty ("last_name").ToString ().ToLower ();
if (name.Contains (word))
visitorList.Add(ToRecord(row.Document));
}
return visitorList;
}

foreach over anonymous types

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;
}

Categories