P
Peter
Hi
I have a list of "Items" which I need to check whether or not it
contains a certain item (based on the item's "id"). What is the "best"
way of doing this?
For example, an Item is declared as the following (actually it's not,
but this is for illustration - Item is a third party class I cannot
change):
public class Item
{
public string Id { get; set; }
public string Name { get; set; }
}
I have a list containing many hundreds of items:
List<Item> itemList = new List<Item>();
I thought of the following 4 methods, a couple using LINQ which I am
only just learning, so my implementations could quite likely be rather
bad. I would appreciate critique of these methods, and opinions on what
is best (fastest, most efficient, prettiest....). As far as I can tell,
my method #1 is fastest.
(1)
A "utility" method:
private bool HasItem(List<Item> itemList, string id)
{
foreach (Item item in itemList)
{
if (item.Id == id)
{
return true;
}
}
return false;
}
(2)
An "extension" method:
public static class ItemListExtension
{
public static bool ContainsItem(this List<Item> itemList, string id)
{
foreach (Item item in itemList)
{
if (item.Id == id)
{
return true;
}
}
return false;
}
}
(3)
LINQ/Lambda:
var a = itemList.FirstOrDefault(itm => itm.Id == findMe);
if (a != null)
{
// list contains the item...
}
(4)
LINQ/query:
var x = (from r in itemList where r.Id == findMe select r).Take(1);
if (x.ToArray().Length > 0)
{
// list contains the item...
}
Thanks,
Peter
I have a list of "Items" which I need to check whether or not it
contains a certain item (based on the item's "id"). What is the "best"
way of doing this?
For example, an Item is declared as the following (actually it's not,
but this is for illustration - Item is a third party class I cannot
change):
public class Item
{
public string Id { get; set; }
public string Name { get; set; }
}
I have a list containing many hundreds of items:
List<Item> itemList = new List<Item>();
I thought of the following 4 methods, a couple using LINQ which I am
only just learning, so my implementations could quite likely be rather
bad. I would appreciate critique of these methods, and opinions on what
is best (fastest, most efficient, prettiest....). As far as I can tell,
my method #1 is fastest.
(1)
A "utility" method:
private bool HasItem(List<Item> itemList, string id)
{
foreach (Item item in itemList)
{
if (item.Id == id)
{
return true;
}
}
return false;
}
(2)
An "extension" method:
public static class ItemListExtension
{
public static bool ContainsItem(this List<Item> itemList, string id)
{
foreach (Item item in itemList)
{
if (item.Id == id)
{
return true;
}
}
return false;
}
}
(3)
LINQ/Lambda:
var a = itemList.FirstOrDefault(itm => itm.Id == findMe);
if (a != null)
{
// list contains the item...
}
(4)
LINQ/query:
var x = (from r in itemList where r.Id == findMe select r).Take(1);
if (x.ToArray().Length > 0)
{
// list contains the item...
}
Thanks,
Peter