I have a list which is created from a Class:
class Vara
{
public int streckKod { get; set; }
public string artNamn { get; set; }
}
And the list looks like this:
List<Vara> minaVaror = new List<Vara>();
And I add to the list with this line:
minaVaror.Add(new Vara() {streckKod = inputBox1, artNamn = textBox2.Text });
But what I'm stuck at is how I can find a specific int within the list. Let's say I'm searching for the item in my list holding the number 293 in the variable streckKod.
I've tried using .IndexOf function but I haven't gotten it to work properly.
Also would it be possible to get the item number that the specific number is located in?
If you want to find all items whose streckKod value is 293 use Where
var items = minaVaror.Where(i => i.streckKod == 293);
If interested in only first item use FirstOrDefault -
var item = minaVaror.FirstOrDefault(i => i.streckKod == 293);
FirstOrDefault will return null in case no item exist in collection with value 293.
Make sure you add namespace System.Linq in your class to use these LINQ extension methods.
Use Linq
minaVarror.Find(item=>item.strekKod == 293);
Adding to Rohit Vats answer...
When you have found your item, with either Where or FirstOrDefault you can get the index by doing:
var item = minaVaror.FirstOrDefault(i => i.streckKod == 293);
// Get index of Vara (item) with streckKod = 293
int index = minaVaror.IndexOf(item);
As IndexOf returns the position of an exact item (Vara) within the list minaVaror
Related
I'm trying to find solution for the next situation:
I have array with Item ids
var arrayIds = new long []{1076,2840,4839,3920,..., N};
I have method which returns one Item
public Item getItem(long id) {
return new Item{Id = id, Name = "name"};
}
Here trying to get all Items
var itemList = new List<Item>();
foreach(var id in arrayIds) {
itemList.Add(getItem(id));
}
Is it possible to use Linq here instead of foreach?
I've tried to write something like that
itemList = arrayIds.ForEach(x => getItem(x));
so I have the next error here:
There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'
So I don't know how to use Linq correctly.
I've tried to write something like that
itemList = arrayIds.ForEach(x => getItem(x));
ForEach() works on List<T>:
arrayIds.ToList().ForEach(x => getItem(x));
But what you want is:
var itemList = arrayIds.Select(getItem).ToList();
Or if you only want to enumerate the items:
var items = arrayIds.Select(getItem);
Use Select
var itemList = arrayIds.Select(x => getItem(x))
I need help, how do I get MAX datatable column value where value LIKE 'N01%'
Basically, if I convert this to SQL:
SELECT MAX(user) FROM tblUser WHERE user LIKE 'N01%'
Thank you.
You can simply do this:
string[] data = {"hello", "N01jaja", "N01ll"};
var userWithN1 = data.Where(we => we.StartsWith("N01")).Max();
StartsWith checks if the element starts with a certain string.
If there's a class then need to implement IComparable.
Sample code:
public class TestClass : IComparable<string>
{
public string Value { get; private set; }
public int CompareTo(string other) { return Value.CompareTo(other); }
}
var result = foo.tblUser.Where(u => u.user.StartsWith("N01")).Max(u => u.user));
Simply use a where statement to start your filter, use a StartsWith to emulate SQL's xx% pattern. Then use Max on a particular column. Though make sure User is something that will actually have a Max value.
In LINQ, I always find it helpful to break the problem down. Here in this case, you have a list of items, you want to narrow down that list with a WHERE clause and return the MAX of the remaining items.
Start
var myItems = db.GetMyList();
WHERE with LIKE
Assuming User is a string variable
myItems = myItems.Where(x=>x.User.StartsWith("N01"));
MAX
var maxItem = myItems.Max(x=>x.User);
All Together
var maxItem = db.GetMyList().Where(x=>x.User.StartsWith("N01")).Max(x=>x.User);
edit - Per comment below, since the search string was 'N01%', is should be starts with and not contains.
I have List of string. If the list contains that partial string then find out the index of that item. Please have a look on code for more info.
List<string> s = new List<string>();
s.Add("abcdefg");
s.Add("hijklm");
s.Add("nopqrs");
s.Add("tuvwxyz");
if(s.Any( l => l.Contains("jkl") ))//check the partial string in the list
{
Console.Write("matched");
//here I want the index of the matched item.
//if we found the item I want to get the index of that item.
}
else
{
Console.Write("unmatched");
}
You can use List.FindIndex:
int index = s.FindIndex(str => str.Contains("jkl")); // 1
if(index >= 0)
{
// at least one match, index is the first match
}
you can use this
var index = s.Select((item,idx)=> new {idx, item }).Where(x=>x.item.Contains("jkl")).FirstOrDefault(x=>(int?)x.idx);
Edit
In case when using a List<string>, FindIndex is better to use.
But in my defence, using FindIndex is not using LINQ as requested by OP ;-)
Edit 2
Should have used FirstOrDefault
This is how I was using it without Linq and wanted to shorten it so posted this question.
List<string> s = new List<string>();
s.Add("abcdefg");
s.Add("hijklm");
s.Add("nopqrs");
s.Add("tuvwxyz");
if(s.Any( l => l.Contains("tuv") ))
{
Console.Write("macthed");
int index= -1;
//here starts my code to find the index
foreach(string item in s)
{
if(item.IndexOf("tuv")>=0)
{
index = s.IndexOf(item);
break;
}
}
//here ends block of my code to find the index
Console.Write(s[index]);
}
else
Console.Write("unmacthed");
}
I have a ListBox (sortedListBox) which I have populated like this by the items in a Combobox (allItemsComboBox):
int index = sortedListBox.FindString(allItemsComboBox.Text, -1);
if (index == -1)
{
var item=new { Text = allItemsComboBox.Text , Value = allItemsComboBox.Value};
sortedListBox.Items.Add(item);
}
The DisplayedMember of sortedListBox is "Text" and ValueMember of it is "Value".
Now I want to iterate through all items in the ListBox and get its values:
public static string ListBoxToString(ListBox lb)
{
List<string> values = new List<string>();
for (int i = 0; i < lb.Items.Count; i++)
{
values.Add(lb.Items[i].ToString());
}
string result = String.Join(",", values);
return result;
}
In this line: values.Add(lb.Items[i].ToString()); I get:
{ Text = "Size" , Value = "cte1.Size"}
I just want to have the value , which is "cte1.Size"
How can I iterate through the items in the ListBox and get the ValueMember of these?
I don't know that there's any way to ask the ListBox to evaluate the ValueMember for you in that way... and because you're using an anonymous type, it becomes harder to get the value.
Options:
Use a named type instead, and cast each item to that
Use dynamic typing
For example:
public static string ListBoxToString(ListBox lb)
{
var values = lb.Items
.Cast<dynamic>()
.Select(x => x.Value.ToString());
return string.Join(",", values);
}
Dynamic typing provides the most immediate fix, but I'd strongly encourage you to consider using a custom type. (It needn't take more than a few lines to write.)
There are two problems with your approach:
1.) The ListBox stores items as a collection of objects which means accessing them with listBox.Items[idx] will only give you back an object and not the actual type. You could get around that with casting it to the appropriate type but it won't work in your case because of the next point.
2.) You create your items as anonymous objects with var item = new { ... }. You can't cast to this kind of type. You could use the dynamic keyword to get around that but I wouldn't do that as you lose type safety.
What you could do is create a simple class for the date you want to store and use that instead of an anonymous type:
class MyData
{
public string Text { get; set; }
public string Value { get; set; }
}
I have a list collection in my class library that uses a sql datareader to returns a list of family details
public class Dataops
{
public List<Details> getFamilyMembers(int id)
{
some of the database code..
List<Details> fammemdetails = new List<Details>();
Details fammember;
while (reader.Read())
{
fammemdetails = new Details((
reader.GetString(reader.GetOrdinal("PHOTO")));
fammemdetails.add(fammember);
}
return fammemdetails;
}
}
So i reference the dll to my project and would like to bind an image to one of my datareader values.
MyProject
DataOps ops = new DataOps();
myimage.ImageUrl = ??? (how do i access the list collections return image value here?
I am able to bind a datasource to the entire method like so
dropdownlistFamily.DataSource = mdb.GetFamilyMembers(id);
But cant figure out how to just grab a single value from there
You can use First/FirstOrDefault, Single/SingleOrDefault depending on your requirement. This would give you a single item from the List and you can access its ImageUrl property.
var item = mdb.GetFamilyMembers(id).FirstOrDefault();
if(item != null)
myimage.ImageUrl = item.ImageUrlProperty;
If you want to get some specific object from the list based on the condition then you can do:
var item = mdb.GetFamilyMembers(id).FirstOrDefault(r=> r.ID == someID);
You may see: LINQ Single vs SingleOrDefault vs First vs FirstOrDefault
You can use FirstOrDefault or SingleOrDefault. Or specify a predicate and use Where.
var firstValue = ops.getFamilyMembers(1).FirstOrDefault();
Use index to access particular record in the collection. You will need to ensure that element exists at the index you given in indexer, otherwise you will get exception. It is zero based index so first element will be at zero index.
var familyMembers = mdb.GetFamilyMembers(id);
if(familyMembers.Count > 0)
myimage.ImageUrl = familyMembers[0].ImageURLProperty;