I have a list as:
var myList = lookuplist;
//where lookupList
Count = 2
[0]: "36"
[1]: ""
Above list is basically being populated by parsing from my excel file. Sorry the code before this is not relevant so not showing that.
My issue is I want to update the empty string with a space. So I tried the code below:
myList .Where(w => w.Length == 0).Select(y=>y = " ").ToList();
But it does not changes anything.
Am I missing something here. I can use a forach to loop through my list but I want to use linq.
Sorry if this is trivial.
You have to assign the updated list back to the original variable. You can do something like this:
myList = myList.Select(y => string.IsNullOrEmpty(y) ? " " : y).ToList();
Related
A little question for a simple LINQ request. This is my first time with LINQ and still not understand all mechanism.
My structure is something like this
List<string> baseData = new List<string>{"\"10\";\"Texte I need\";\"Texte\"",
"\"50\";\"Texte I need\";\"Texte\"",
"\"1000\";\"Texte I need\";\"Texte\"",
"\"100\";\"Texte I need\";\"Texte\""};
Each line of data is construct with field separator ";" and each field are encapsule with quote ".
I have another List Compose with value i have to find in my first list. And i have the Position in line i have to search. because "Texte I need" can be equal with value i am searching
List<string> valueINeedToFind = new List<string>{"50","100"};
char fieldSeparator = ';';
int fieldPositionInBaseDataForSearch = 0;
int fieldPositionInBaseDataToReturn = 1;
I made a first Linq to extract only Line interested me.
List<string> linesINeedInAllData = baseData.Where(Line => valueINeedToFind.Any(Line.Split(fieldSeparator)[fieldPositionInBaseDataForSearch].Trim('"').Contains)).ToList();
This first request Work Great and now i have only Data Line Interested me.
My problem is I don't want all the line But only a list of the value "Texte I need" in position FieldPositionInBaseDataToReturn.
I have to made another LINQ or can i modify my first to directly get what I need?
Since you will be using the split version of each line more than once, separate out the Split operation and then work on the resulting array:
List<string> linesINeedInAllData = baseData.Select(Line => Line.Split(fieldSeparator))
.Where(splitLine => valueINeedToFind.Any(splitLine[fieldPositionInBaseDataForSearch].Trim('"').Contains))
.Select(splitLine => splitLine[fieldPositionInBaseDataToReturn])
.ToList();
List<string> linesINeedInAllData = baseData.Where(Line => valueINeedToFind.Any(Line.Split(fieldSeparator)[fieldPositionInBaseDataForSearch].Trim('"').Equals)).ToList()
.Select(Line => Line.Split(fieldSeparator)[fieldPositionInBaseDataToReturn].Trim('"').ToList();
I have a combo-box that contains lots of entries like this small extract
1R09ST75057
1R11ST75070
1R15ST75086
1R23ST75090
2R05HS75063
2R05ST75063
3R05ST75086
2R07HS75086
The user now enters some information in the form that result in a string being produced that has a wildcat (unknown) character in it at the second character position
3?05ST75086
I now want to take this string and search\filter through the combo-box list and be left with this item as selected or a small set of strings.
If I know the string without the wildcat I can use the following to select it in the Combo-box.
cmbobx_axrs75.SelectedIndex = cmbobx_axrs75.Items.IndexOf("2R05HS75063");
I thought I could first create a small subset that all have the first char the same then make a substring of each minus the first two chars and check this but I can have a large amount of entries and this will take too much time there must be an easier way?
Any ideas how I can do this with the wildcat in the string please?
Added info:
I want to end up with the selected item in the Combobox matching my string.
I choose from items on the form and result in string 3?05ST75086. I now want to take this and search to find which one it is and select it. So from list below
1R05ST75086
2R05ST75086
3R05ST75086
6R05ST75086
3R05GT75086
3R05ST75186
I would end up with selected item in Combo-box as
3R05ST75086
You could use regular expressions. Something like this:
string[] data = new string[]
{
"1R09ST75057",
"1R11ST75070",
"1R15ST75086",
"1R23ST75090",
"2R05HS75063",
"2R05ST75063",
"3R05ST75086",
"2R07HS75086"
};
string pattern = "3*05ST75086";
string[] results = data
.Where(x => System.Text.RegularExpressions.Regex.IsMatch(x, pattern))
.ToArray();
You can use a regular expression for this task. First, you need a method to convert your pattern string to Regex like this (it should handle "*" and "?" wildcards):
private static string ConvertWildCardToRegex(string value)
{
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
Then you will use it like the following:
List<string> comboBoxValues = new List<string>()
{
"1R09ST75057",
"1R11ST75070",
"1R15ST75086",
"1R23ST75090",
"2R05HS75063",
"2R05ST75063",
"3R05ST75086",
"2R07HS75086"
};
string searchPattern = "3?05ST75086";
string patternAsRegex = ConvertWildCardToRegex(searchPattern);
var selected = comboBoxValues.FirstOrDefault(c => Regex.IsMatch(c, patternAsRegex));
if (selected != null)
{
int selectedIndex = comboBoxValues.IndexOf(selected);
}
This assumes you only care about first found match. If you need all matches then substitute FirstOrDefault(...) with Where(...) clause and swap "if" statement with a foreach loop.
Thanks to all that helped I used a combination of items from all answers so everyone helped me answer this.
I added this function from the answers as it seems a good idea, thanks
private static string ConvertWildCardToRegex(string value)
{
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
Then I get the combo box items into a list. I search the list and make some more decisions based on the result of the search.
List<string> comboBoxValues = new List<string>();
for (int i = 0; i < cmbobx_in_focus.Items.Count; i++)
{
comboBoxValues.Add(cmbobx_in_focus.GetItemText(cmbobx_in_focus.Items[i]));
}
string[] results = comboBoxValues
.Where(x => Regex.IsMatch(x, ConvertWildCardToRegex(lbl_raster_used.Text)))
.ToArray();
I now have array called results which is easy to work with.
Hello I'm new to linq and lambda
I have two lists
fl.LocalOpenFiles ...
List<string> f....
there is a property (string) for example taking index 0
fl.LocalOpenFiles[0].Path
i wanted to select all from the first list fl.LocalOpenFiles where fl.LocalOpenFiles.Path starts with a string from the List<string> f
I finally got this...
List<LocalOpenFile> lof = new List<LocalOpenFile>();
lof = fl.LocalOpenFiles.Join(
folders,
first => first.Path,
second => second,
(first, second) => first)
.ToList();
But its just selecting folders that meet the requirement first.Path == second and i couldnt find a way to get the data that i want which is something meeting this "braindump" requirement:
f[<any>] == fl.LocalOpenFiles[<any>].Path.Substring(0, f[<any>].Length)
Another Example...
List<string> f = new List<string>{ "abc", "def" };
List<LocalOpenFile> lof = new List<LocalOpenFile>{
new LocalOpenFile("abc"),
new LocalOpenFile("abcc"),
new LocalOpenFile("abdd"),
new LocalOpenFile("defxsldf"),)}
// Result should be
// abc
// abcc
// defxsldf
I hope i explained it in a understandable way :)
Thank you for your help
Do you mean something like this :
List<LocalOpenFile> result =
lof.Where(file => f.Any(prefix => file.Path.StartsWith(prefix)))
.ToList();
You can use a regular where instead of a join, which will give you more straight forward control over the selection criteria;
var result =
from file in lof
from prefix in f
where file.Path.StartsWith(prefix)
select file.Path; // ...or just file if you want the LocalOpenFile objects
Note that a file matching multiple prefixes may show up more than once. If that is a problem, you can just add a call to Distinct to eliminate duplicates.
EDIT:
If you - as it seems in this case - only want to know the matching path and not the prefix it matches (ie you only want data from one collection as in this case), I'd go for #har07's Any solution instead.
I saw many examples of getting the values from selectedItems, but in my case I would like to somehow separate these values. What I mean is, for example if I have in my list options like work home forrest car, I would like to be able after choosing work and home to get both text separated and save them in some string variable.
Now I am doing it this way:
string text = "";
foreach (var item in customListBox1.SelectedItems)
{
text += item.ToString() + " ";
}
Later I am filtering datagridview based on this selecteditems in such way:
var result = list3.Where(Srodek => Srodek.Srodek.category1 == text);
That is why I need them separated. How can I do it?
If something is not clear, please let me know, I will try to explain it more.
You can do something better like this:
string text = string.Join(",", customListBox1.SelectedItems.OfType<Object>().Select(x => x.ToString()).ToArray());
var list = customListBox1.SelectedItems.Cast<string>().ToList();
var result = list3.Where(Srodek => list.Any(x=>x == Srodek.Srodek.category1));
The following lines of code grabs a handful of rows from a database, and puts the value Table.Id into a list of integers. I imagine there is a way to condense this code into a single line, but I'm not sure how.
var result db.Table.Where(a=>a.Value>0).ToList();
List<int> ids = new List<int>();
foreach(var row in result){
ids.Add(row.Id);
}
Any help would be appreciated, thanks!
Edit: My title says array, my example has a list, either one is fine. Sorry if there was any confusion.
var ids = db.Table.Where(a => a.Value > 0).Select(row => row.Id).ToList();
Should do the trick unless my fu is off
Try this:
var result = db.Table.Where(a=>a.Value>0)
.Select(a=>a.Id)
.ToList();
You can also use the List.ForEach Method. So something like:
db.Table.Where(a=>a.Value>0).ToList().ForEach(delegate(Table row) { ids.Add(row.Id); });