How to get the Split value from collection [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have the following key value pair in an array, and am trying to extract and load them into a collection.
The below code is working but it can be optimized using linq:
string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true";
List<WebSiteAddress> _websiteList = new List<WebSiteAddress>() ;
WebSiteAddress _website = new WebSiteAddress();
string[] _websiteData = _divider[1].Split('=');
string[] _WebsiteKeyValuePair = _websiteData[1].Split(',');
for (int j = 0; j < _WebsiteKeyValuePair.Length; j++)
{
string key = _WebsiteKeyValuePair[j].Split(':')[0];
string value = _WebsiteKeyValuePair[j].Split(':')[1];
if (key.ToLower() == "url")
{
_initWebsite.Url = value;
}
else if (key.ToLower() == "isdefault")
{
_website.IsDefault = Convert.ToBoolean(value);
_websiteList.Add(_website);
}
}

You can do something like:
string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true";
List<WebSiteAddress> _websiteList = _data
.Split(new string[]{"url:"}, StringSplitOptions.RemoveEmptyEntries)
.Select(site => site.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries))
.Where(site => site.Length > 1)
.Select(site => new WebSiteAddress { Url = site[0], IsDefault = site[1].ToLower().Replace("isdefault:", "") == "true"})
.ToList();

Related

C# string split into one or two variables [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In C# I am passing a single string value to a function. The value is similar to this: "XA=12345678;BK=AZ31" or "XA=87654321", sometimes the BK= is there, sometimes it is not. But if it's present, I need it for my function.
I've made this attempt:
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
string XA_EQ = "";
string BK_EQ = "";
foreach(string item in item_list)
{
BK_EQ = "";
string[] split = item.Split(';');
XA_EQ = split[0];
if(split.length == 2)
BK_EQ = split[1];
my_func(XA_EQ, BK_EQ);
}
Is there a better way to do this? This works, but it seems inconvenient.
RegEx approach
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach (string item in item_list)
{
string XA_EQ = Regex.Match(item, "(?<=XA=)[0-9A-Z]*").Value;
string BK_EQ = Regex.Match(item, "(?<=BK=)[0-9A-Z]*").Value;
my_func(XA_EQ, BK_EQ);
}
https://dotnetfiddle.net/6xgBi3
I suggest Splitting initial strings into Dictionary:
using System.Linq;
...
private static Dictionary<string, string> GetVariables(string source) {
return source
.Split(';')
.Select(pair => pair.Split('='))
.ToDictionary(pair => pair[0].Trim(), pair => pair[1].Trim());
}
Now we can analyze values:
string[] item_list = new string[] { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list) {
var namesAndValues = GetVariables(item);
// If we have XA variable, assign its value to XA_EQ, otherwise assign ""
string XA_EQ = namesAndValues.TryGetValue("XA", out string xa) ? xa : "";
// If we have "BK" variable, call my_func with it
if (namesAndValues.TryGetValue("BK", out string BK_EQ)) {
// If we have "BK" variable
my_func(XA_EQ, BK_EQ);
}
}
Easy to read solution with LINQ:
string[] itemList = { "XA=12345678;BK=AZ31", "XA=87654321" };
itemList.Select(x => x.Split(";")).ToList().ForEach(i =>
{
string XA_EQ = i.FirstOrDefault();
string BK_EQ = i.Skip(1).FirstOrDefault();
my_func(XA_EQ, BK_EQ != null ? BK_EQ : "");
});
You don't get the actual value of XA or BK this way, but since you mention that this works for you I'm implementing the same logic.
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list)
{
if item.Contains('BK') {
string[] split = item.split(';');
my_func(split[0], split[1]);
} else {
my_func(item, null);
}
}

get a total value from loop items [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Check the code bellow. I am looping to get all value of a returned XML response. But i want to get a total value of all nofwatch variable. How can i add them to get a total value? any idea?
foreach (var sri in searchResultItems)
{
// Get all xml elements
var childElements = sri.Elements();
var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
.Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");
//add items from xml data to EbayDataViewModel object
items.Add(new EbayDataViewModel
{
TotalWatchers = nofwatch.Value //how can do + result of all nofwatch value?
});
ViewBag.TotalWatchers = TotalWatchers;
}
var totalValue = 0; //delcare the variable outside the foreach loop
foreach (var sri in searchResultItems)
{
// Get all xml elements
var childElements = sri.Elements();
var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
.Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");
//now use += operator to add the result to the totalValue variable
//totalValue += nofwatch.Value;
//nofwatch.Value should be of type string and you would need to parse it as an integer first if that truely is the case
var intValue = 0;
if (int.TryParse(nofwatch.Value, out intValue) == false)
continue;
totalValue += intValue;
}
//outside of the foreach loop use totalValue to set the desired member
ViewBag.TotalWatchers = totalValue;

What to return if condition is not satisifed? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The method looks as following:
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
var result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
return result;
}
}
It's obvious that not all paths return something and the issue is I can't return null.
How to rearrange the method?
Maybe you can initialize your List?
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
List<string> result = new List<string>()
{
owner,
string.Empty,
string.Empty
};
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
}
return result;
}
I usually do this when I want to create an assembler method for example to tranform a List<X> to another List<Y>, so if my List<X> is null I try to return an empty List of Y. I prefer to do this instead of throwing exceptions and getting my Dashboard full of errors. But It depends on how your codes works.

I want to split string with "," but from 2nd comma(,) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to split string with "," but from 2nd comma(,)
haven't tried it, but you will need something like this:
string pattern = "|\*,";
string[] result = Regex.Split(before_split, pattern);
If you are looking for skip first ',' & then split rest of the string by ',' then you can try following.
string before_split = "pune,mumbai|01234,delhi|65432,Bhopal|09231,jabalpur|0987765";
var firstPart = before_split.Substring(0, before_split.IndexOf(",", System.StringComparison.Ordinal));
var stringToProcess = before_split.Substring(before_split.IndexOf(",", System.StringComparison.Ordinal) + 1);
var stringSegments = stringToProcess.Split(',');
Console.WriteLine("{0},{1}",firstPart ,stringSegments[0]);
for (var i = 1; i < stringSegments.Length; i++)
{
Console.WriteLine(stringSegments[i]);
}
Try this, the final result is on a List finalSplit
string before_split = "pune,mumbai|01234,333,222,delhi|65432,Bhopal|09231,jabalpur|0987765";
string[] split1 = before_split.Split(',');
List<string> finalSplit = new List<string>();
string aux = "";
foreach (string s in split1)
{
if (s.IndexOf('|') == -1)
aux = aux + s + ',';
else
{
if (aux == "")
aux = s;
else
aux = aux + s;
finalSplit.Add(aux);
aux = "";
}
}
Hope it helps
My solution is
string before_split = "pune,mumbai|01234,delhi|65432,Bhopal|09231,123,jabalpur|0987765";
string buffer = "";
var parts = before_split.Split(',');
var lines = parts.Select(p =>
{
if (p.Contains('|'))
{
var line = buffer == "" ? p : buffer + ',' + p;
buffer = "";
return line;
}
else
{
buffer = buffer == "" ? p : buffer + ',' + p;
return null;
}
}).Where(p => p != null).ToArray();
How about this...
Regex rex = new Regex("[a-zA-Z]+[a-zA-Z,]*[|]+[0-9]+");
var result = rex.Matches("pune,mumbai|01234,delhi|65432,Bhopal|09231,jabalpur|0987765").Cast<Match>()
.Select(m => m.Value)
.ToArray()
var result =before_split.Split(',')

using HtmlAgilityPack [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a problem HtmlAgilityPack, I would like the following image. but it does not coincide with the lines. What can I do?
HtmlWeb web = new HtmlWeb();
web.OverrideEncoding = Encoding.GetEncoding("windows-1254");
HtmlAgilityPack.HtmlDocument doc = web.Load("http://www.yerelnet.org.tr/belediyeler/belediye.php?belediyeid=129531");
var nufus = doc.DocumentNode.SelectNodes("/html/body/center/table/tr/td[2]/table/tr[2]/td[2]/table/tr[2]/td/table/tr/td/table[5]/tr/td[2]/table/tr/td[3]/table[2]");
string str = String.Empty;
string line = String.Empty;
if (nufus != null)
{
for (int i = 0; i < nufus.Count; i++)
{
str += nufus[i].InnerText.Replace(" ", "").Replace("\t", "").Replace("Nüfus Bilgileri", "");
string[] s = str.Split('\n');
for (int x = 10; x < s.Count(); x++)
{
if (s[x] != String.Empty && s[x] != " ")
{
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
}
}
}
}
dataGridView1.DataSource = lnufus.GroupBy(x => x).Select(g => new
{
Yıl = g.Key, Toplam = g.Key, Kadin = g.Key, Erkek = g.Key
}).ToList();
No need for that strange xpath query. This should work
var nufus = doc.DocumentNode.SelectNodes("//table[#class='belediyeler']/tr")
.Skip(1)
.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())
.Select(td => new { Yil = td[0], Toplam = td[1], Kadin = td[2], Erkek = td[3] })
.ToList();
dataGridView1.DataSource = nufus;

Categories