How can I find a specific element in a ListT?
Use a lambda expression
MyClass result = list.Find(x => x.GetId() == "xy");
Note: C# has a built-in syntax for properties. Instead of writing getter and setter as ordinary methods (as you might be used to from Java), write
private string _id;
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
value
is a contextual keyword known only in the set accessor. It represents the value assigned to the property.
Since this pattern is often used, C# provides auto-implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).
public string Id { get; set; }
You can simply use properties as if you were accessing a field:
var obj = new MyClass();
obj.Id = "xy"; // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id; // Calls the getter.
Using properties, you would search for items in the list like this
MyClass result = list.Find(x => x.Id == "xy");
You can also use auto-implemented properties if you need a read-only property:
public string Id { get; private set; }
This enables you to set the Id
within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter
public string Id { get; protected set; }
And finally, you can declare properties as virtual
and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.
Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer
public string Id { get; } = "A07"; // Evaluated once when object is initialized.
You can also initialize getter-only properties within the constructor instead. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.
This works also with read-write auto-properties:
public string Id { get; set; } = "A07";
Beginning with C# 6.0 you can also write properties as expression-bodied members
public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }
See: .NET Compiler Platform ("Roslyn")
New Language Features in C# 6
Starting with C# 7.0, both, getter and setter, can be written with expression bodies:
public string Name
{
get => _name; // getter
set => _name = value; // setter
}
Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0
is equivalent to x = (y = (z = 0))
and has the same effect as the statements x = 0; y = 0; z = 0;
.
Since C# 9.0 you can use read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.
public string Name { get; init; }
var c = new C { Name = "c-sharp" };
Beginning with C# 11, you can have a required
property to force client code to initialize it.
The field
keyword is planned for a future version of C# (it did not make it into C# 11) and allows the access to the automatically created backing field.
// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }
public Data LazyData => field ??= new Data();
Find element in List that contains a value
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
how to check if ListT element contains an item with a Particular Property Value
If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex
instance method. Such as
int index = list.FindIndex(f => f.Bar == 17);
Where f => f.Bar == 17
is a predicate with the matching criteria.
In your case you might write
int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0)
{
// element exists, do what you need
}
Check if list contains element that contains a string and get that element
You should be able to use Linq here:
var matchingvalues = myList
.Where(stringToCheck => stringToCheck.Contains(myString));
If you simply wish to return the first matching item:
var match = myList
.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));
if(match != null)
//Do stuff
How can I get the index of an item in a list in a single step?
How about the List.FindIndex Method:
int index = myList.FindIndex(a => a.Prop == oProp);
This method performs a linear search; therefore, this method is an
O(n) operation, where n is Count.
If the item is not found, it will return -1
Get previous/next item of a given item in a List
You can use indexer to get element at desired index. Adding one to index will get you next and subtracting one from index will give you previous element.
int index = 4;
int prev = list[index-1];
int next = list[index+1];
You will have to check if next and previous index exists other wise you will get IndexOutOfRangeException exception. As List is zero based index so first element will have index 0
and second will have 1
and so on.
if(index - 1 > -1)
prev = list[index-1];
if(index + 1 < list.Length)
next = list[index+1];
Python: Find in list
As for your first question: "if item is in my_list:
" is perfectly fine and should work if item
equals one of the elements inside my_list
. The item must exactly match an item in the list. For instance, "abc"
and "ABC"
do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3
.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in
operator for that:
3 in [1, 2, 3] # => True
Filtering a collection
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter
doesn't return a list, but a generator-like object.
Finding the first occurrence
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else
clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration
if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
Finding the location of an item
For lists, there's also the index
method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index
always returns the lowest index:......
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate()
instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
How to find an element in a ListT where name is the same and its time is the same or at least similar?
Presuming Id and Value combination makes unique value:
class Program
{
static List<A> firstList;
static List<A> secondList;
static List<A> resultList;
static void Main(string[] args)
{
// Fill firstList, secondList with data <your server methodes>
resultList = new List<A>();
foreach (var item in firstList)
{
var match = secondList.Find(a => a.Equals(item));
if (match != null)
{
if (item.Id == "123")
{
item.Value += match.Value;
}
else
{
item.Value += 45;
}
}
resultList.Add(item);
}
resultList.AddRange(secondList.Except(firstList));
}
}
public class A
{
public string Id;
public float Value;
public override bool Equals(Object obj)
{
if ((obj == null) || !GetType().Equals(obj.GetType()))
{
return false;
}
else
{
var a = (A)obj;
return (Id == a.Id) && (Value == a.Value);
}
}
}
Check count of a specific element inside a list in C#
You can use System.Linq
for that
var count = points.Count(p => p.X == 5);
Related Topics
Easiest Way to Read from a Url into a String in .Net
How to Ensure a Form Displays on the "Additional" Monitor in a Dual Monitor Scenario
How to Disable a Tab Inside a Tabcontrol
How to Unload an Assembly from the Primary Appdomain
How to Hide a Column (Gridview) But Still Access Its Value
Recursive Hierarchy - Recursive Query Using Linq
Convert Array of Bytes to Bitmapimage
Icecast 2: Protocol Description, Streaming to It Using C#
Routing: the Current Request for Action [...] Is Ambiguous Between the Following Action Methods
Built in .Net Algorithm to Round Value to the Nearest 10 Interval
Cannot Access a Disposed Object in ASP.NET Core When Injecting Dbcontext
How to Seed in Entity Framework Core 2
Getting/Setting File Owner in C#
How Is Performance Affected by an Unused Using Directive
Understanding .Asenumerable() in Linq to SQL