how to display only the value that has diacritic - c#

I have found a way how to display the list without diacritic but how to display it with diacritic ? Here I am checking if the value is in the list twice, if it is then I need to display the one with diacritic but how do I check for diacritic?
{
var fields = new List<Field>()
{
new Field{ Value ="Kateřina Kučerová", IdentityDocumentFieldType = IdentityDocumentFieldType.unknown},
new Field{ Value = "Katerina Kucerova", IdentityDocumentFieldType = IdentityDocumentFieldType.Document},
};
foreach (var field in fields)
{
var value = field.Value;
//Console.WriteLine(StringExtenstion.RemoveDiacritics(value));
var exists = fields.Any(r => r.Desc == field.Desc);
if (!exists)
{
Console.WriteLine(field.Value);
}
else
{
Console.WriteLine(field.Value);
}
}}

string input =#"Kateřina Kučerová";
var samo = "řčěáíéě";
foreach (char c in samo)
{
if(input.Contains(c))
Console.WriteLine("ok");
}
This is what I needed

Related

XDocument get Element value with Namespace (RSS Feed)

Im working on getting some values from an RSS feed but i am having difficulties getting a value which has the namespace in the element tag. I've tried adding the namespace to the lookup of the value but i always get null
Any idea on how this is achieved?
Feed
https://wegotthiscovered.com/movies/feed/
Element
xmlns:content="http://purl.org/rss/1.0/modules/content/"
Namespace
content:encoded
public async Task<bool> GetNewsFeeds()
{
Database db = new Database();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("https://wegotthiscovered.com/movies/feed/", "Movie");
dictionary.Add("https://wegotthiscovered.com/blu-ray/feed/", "Blu-ray");
dictionary.Add("https://wegotthiscovered.com/reviews/feed/", "Reviews");
dictionary.Add("https://wegotthiscovered.com/featured/feed/", "Featured");
dictionary.Add("https://wegotthiscovered.com/galleries/feed/", "Galleries");
db.DeletMovieNews();
foreach (var pair in dictionary.ToList())
{
try
{
if (PhysicalDevice.HasInternetConnection())
{
XDocument doc = XDocument.Load(pair.Key);
XNamespace nsSys = "http://purl.org/rss/1.0/modules/content/";
var entries = (from item in doc.Descendants("item")
select new Movie_News
{
Content = item.Element(nsSys + "encoded").Value, // ISSUE HERE
Link = item.Element("link").Value,
PublishedDate = item.Element("pubDate").Value,
Title = item.Element("title").Value,
Description = item.Element("description").Value,
GroupName = "News",
FeedName = pair.Value
});
List<Movie_News> newsCollection = entries.ToList();
if (newsCollection.Count() != 0)
{
using (var rateGate = new RateGate(40, TimeSpan.FromSeconds(10)))
{
rateGate.WaitToProceed();
foreach (Movie_News item in newsCollection)
{
string regex = #"((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?";
Match match = Regex.Match(item.Description, regex);
if (match.Success)
{
item.ImageUrl = match.Value;
item.B64Image = await DownloadImage(item.ImageUrl);
}
item.Description = item.Description.Remove(0, item.Description.IndexOf("</div>"));
item.Description = item.Description.Replace("</div>","");
db.InsertNewsData(item);
}
}
}
return true;
}
}
catch(Exception ex)
{
return false;
}
}
return true;
}
}
Typical , soon as i completed the write up, its working now

How to remove a word that already exist in errorList

I have a method that runs spellcheck in a word, but what i want here is that if the word already exist in my errorlist it should not be add as error. below is my code.
public void CheckSpelling()
{
int lineno = 0;
bool start = false;
foreach (string line in _contentList)
{
lineno++;
if (line.Contains("<text>"))
{
start = true;
}
if (start)
{
foreach (Match match in Regex.Matches(line, "<.*?>[^<]+</(.*?)>", RegexOptions.IgnoreCase))
{
List<string> customdiclist = new List<string>(File.ReadAllLines(Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["customdic"])));
string[] strArray = Regex.Replace(match.Value, "</?[^>]+>", string.Empty).Split(' ');
foreach (string word in strArray)
{
if ((word.Trim() != string.Empty) && ((word.Substring(0, 1) != word.Substring(0, 1).ToUpper()) && !_helper.CheckSpelling(Regex.Match(word, "[a-zA-Z]+").Value) && !customdiclist.Contains(word)))
{
ErrorModel errorModel = new ErrorModel()
{
LineNumber = lineno,
ErrorMessage = "Please Check Misspelled words",
Text = word
};
ErrorList.Add(errorModel);
}
}
}
}
}
}
_helper.CheckSpelling
class Helper
{
private static readonly string DictPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["dictionary"]);
private readonly Hunspell _splCheck = new Hunspell(DictPath + #"\nl_NL.aff", DictPath + #"\nl_NL.dic");
public bool CheckSpelling(string strWord)
{
if(!_splCheck.Spell(strWord.Trim()))
{
return false;
}
return true;
}
}
Can some one help, I dont want any duplicate word in my errorlist.
You can use LINQ to check if your ErrorList already contains an ErrorModel object with a Text property which has the value of the word you are checking.
Using FirstOrDefault you can check to see if it returns a null. If an item cannot be found in the list, a null will be returned as the default value because your list is a collection of class objects (whose default value is null).
If the FirstOrDefault returns null then the word has not been added to the ErrorList.
For more information see When to use .First and when to use .FirstOrDefault with LINQ?.
foreach (string word in strArray)
{
if ((word.Trim() != string.Empty) && ((word.Substring(0, 1) != word.Substring(0, 1).ToUpper()) && !_helper.CheckSpelling(Regex.Match(word, "[a-zA-Z]+").Value) && !customdiclist.Contains(word)))
{
if (ErrorList.FirstOrDefault(e => e.Text == word) == null)
{
ErrorModel errorModel = new ErrorModel()
{
LineNumber = lineno,
ErrorMessage = "Please Check Misspelled words",
Text = word
};
ErrorList.Add(errorModel);
}
}
}

Setting RouteValueDictionary html attributes differently on first object in a foreach loop

I have a fairly large method which is returning Radio buttons based fundamentally on an enum.
foreach (var name in names)
{
//other stuff
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", true } }; //<- I want this to be true on first, false on everything after
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
//more stuff
}
I am arranging my array names in a certain order before I drop into the loop, the order stipulates that the first radio button should be checked when finally rendered to my page, and this is what I'm struggling with as, it is checking each and every item in the for each, resulting in the last item to go through being the one left checked.
I have tried adding something like:
bool firstRadioButton = true;
...outside the loop however I am loosing the reference to attribs etc. when I start placing them inside if statements and I cant seem to declare them without their required parameters outside the if statements.
Can anyone suggest a way that I can only set checked to true for attribs on the first pass of the foreach?
It's not clear what you were doing with firstRadioButton, but something like this should work:
bool firstRadioButton = true;
foreach (var name in names)
{
// ....
RouteValueDictionary attribs = null;
if (firstRadioButton)
{
attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", true } }; //<- I want this to be true on first, false on everything after
firstRadioButton = false;
}
else
{
attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }};
}
// ...
}
Use instead foreach loop for.
for (int i = 0; i < names.length; i++)
{
var name = names[i];
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", i == 0 ? true : false} };
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
}
Or in foreach you can do
bool isFirst = true;
foreach (var name in names)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", isFirst} };
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
if(isFirst)
{
isFirst = false;
}
}

How to Set default combobox

So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.
Actually, it works if I create a simple combobox and use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.
This is how I fill my combo box (located in the class's constructor);
string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
List<string[]> list = database.Select(command, false);
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.
WinForms, by the way.
Thank you in advance.
cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like
cbxCategory.SelectedIndex = 2;
your
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")
should return -1 as long as no ComboboxItem mutches the string ("New");
another solution though i don't like it much would be
foreach(object obj in cbxCategory.Items){
String[2] objArray = (String[])obj ;
if(objArray[1] == "New"){
cbxCategory.SelectedItem = obj;
break;
}
}
perhaps this also requires the following transformation to your code
foreach (string[] result in list)
{
cbxCategory.Items.Add(result);
}
I haven't tested the code and i am not sure about the casting to String[2] but something similar should work
It looks like you're searching the cbxCategory.Items collection for a string, but it contains items of type ComboBoxItem. Therefore the search will return -1.
You can use LINQ.
//string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
//List<string[]> list = database.Select(command, false);
// sample data...
List<string[]> list = new List<string[]> { new string[] { "aaa", "bbb" }, new string[] { "ccc", "ddd" } };
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
ComboBoxItem tmp = cbxCategory.Items.OfType<ComboBoxItem>().Where(x => x.ResultFirst == "bbb").FirstOrDefault();
if (tmp != null)
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(tmp);
ComboBoxItem class:
class ComboBoxItem
{
public string ResultFirst { get; set; }
public string ResultSecond { get; set; }
public ComboBoxItem(string first, string second)
{
ResultFirst = first;
ResultSecond = second;
}
}
Here's my simple solution
var list = comboBox1.Items.Cast<string>().ToList();
cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
My solution:
int? defaultID = null;
foreach (DataRow dr in dataSource.Tables["DataTableName"].Rows)
{
if ((dr["Name"] != DBNull.Value) && ((string)dr["Name"] == "Default Name"))
{
defaultID = (int)dr["ID"];
}
}
if (defaultID != null) comboBox.SelectedValue = defaultID;

Get value from column using a column name string c#

I have 2 lists..
The first contains rows with mapping values inlcuding column name, xcord, ycord
The second contains the data I need to map..
I need to get the value in each row using the column name from the first row..
for example
List<SheetMappings> smaps = new List<SheetMappings>();
foreach(maplist m in mlist)
{
SheetMappings newMap = new SheetMappings();
foreach(vallist v in vlist)
{
newMap.Value = v.{m.ColumnName};
newMap.xCord = m.xCord;
newMap.yCord = m.yCord;
}
smaps.Add(newMap);
}
Any assitance appreciated
Cheers
Graham
EDIT:
List<SpreadMappings> spreadMapping = new List<SpreadMappings>();
foreach (var m in mappings)
{
foreach (var v in hvalues)
{
SpreadMappings map = new SpreadMappings();
switch (m.ColumnName)
{
case “DocHeading”:
map.ColumnX = m.ColumnX;
map.ColumnY = m.ColumnY;
map.ColumnValue = v.DocHeading;
map.ColumnName = m.ColumnName;
map.ColumnId = v.Id;
map.ColumnSheetName = sheetName; spreadMapping.Add(map);
break;
If I understand what you're trying to do, you'll need to use reflection to get the value of the property represented by m.ColumnName:
var smaps = new List<SheetMappings>();
foreach(maplist m in mlist)
{
var pi = typeof(vallist).GetProperty(m.ColumnName);
var newMap = new SheetMappings();
foreach(vallist v in vlist)
{
newMap.Value = pi.GetValue(v, null);
newMap.xCord = m.xCord;
newMap.yCord = m.yCord;
}
smaps.Add(newMap);
}
So that's using reflection to get a reference to the PropertyInfo for the property represented by m.ColumnName, then calling PropertyInfo.GetValue to get the value of that property from v.
Well I think the "newMap.Value = v.{m.ColumnName}" part would be something like:
newMap.Value = v.FirstOrDefault( vitem => vitem.ColumnName == m.ColumnName );
This would give you the first item within "v" that has a "ColumnName" property that matches the "ColumnName" property of "m". This assumes that the contents of "vallist" are objects that have a "ColumnName" property.

Categories

Resources