Checking if a list of objects contains a property with a specific value
You can use the Enumerable.Where extension method:
var matches = myList.Where(p => p.Name == nameToExtract);
Returns an IEnumerable<SampleClass>
. Assuming you want a filtered List
, simply call .ToList()
on the above.
By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:
var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));
See also
how to check if List<T> 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
}
How can I find a specific element in a List<T>?
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" };
A feature is discussed for a future version of C#: The field
keyword allowing the access to the automatically created backing field.
// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }
How do I get the count of attributes that an object has?
Since the attributes are on the properties, you would have to get the attributes on each property:
Type type = typeof(StaffRosterEntry);
int attributeCount = 0;
foreach(PropertyInfo property in type.GetProperties())
{
attributeCount += property.GetCustomAttributes(false).Length;
}
How to count the number of elements that match a condition with LINQ
int divisor = AllMyControls.Where(p => p.IsActiveUserControlChecked).Count()
or simply
int divisor = AllMyControls.Count(p => p.IsActiveUserControlChecked);
Since you are a beginner, it would be worthwhile to take a look at Enumerable
documentation
C# List of objects, how do I get the sum of a property
using System.Linq;
...
double total = myList.Sum(item => item.Amount);
How to get a list of properties with a given attribute?
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]()
.
Linq select object from list depending on objects attribute
First, Single
throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct
property is true
. Right now, you are checking if a
is equal to a.Correct
(which will not even compile).
You should use First
(which will throw if there are no such elements), or FirstOrDefault
(which will return null
for a reference type if there isn't such element):
// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct);
// this will return the first correct answer,
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct);
// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();
c# - How to get sum of the values from List?
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
int total = monValues.Sum(x => Convert.ToInt32(x));
Get count of all items in a list that have one of the properties in another list
Sure, you can just loop through the values and, for each one, get the count of items that have Property == value
.
In the sample below, I'm selecting an anonymous type that contains the Value
and the Count
of each item that has Property == value
:
public class Data
{
public int Id { get; set; }
public int Property { get; set; }
}
public class Program
{
private static void Main()
{
var allData = new List<Data>
{
new Data {Id = 1, Property = 1},
new Data {Id = 2, Property = 1},
new Data {Id = 3, Property = 2},
};
var values = new[] {1, 2};
var results = values.Select(value =>
new {Value = value, Count = allData.Count(item => item.Property == value)});
foreach (var result in results)
{
Console.WriteLine($"{result.Count} objects with Property {result.Value}");
}
}
}
Output
Related Topics
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
How to Get Number of Rows Using Sqldatareader in C#
How to Create a Dynamic Email Template That Can Be Modified Without Changing Code in C# .Net MVC
How to Check Byte Array Empty or Not
Clearing a Textbox Leaves an Invisible Character
How to Download a File from a Url in C#
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
How to Authenticate a Webclient Request
How to Refresh an Entity Framework Core Dbcontext
How to Correctly Write Parallel.For With Async Methods
How to Remove Windows Credentials
Passing Datetimeoffset as Webapi Query String
Reference External Dll in .Net Core Project
Asp.Net Core, Change Default Redirect for Unauthorized