Home >Backend Development >C++ >How to Add, Sort, and Filter Dynamic Properties in C#?

How to Add, Sort, and Filter Dynamic Properties in C#?

DDD
DDDOriginal
2025-01-05 04:00:40525browse

How to Add, Sort, and Filter Dynamic Properties in C#?

Creating Dynamic Properties in C#

In C#, static properties can be created for a class. However, requirements may arise to dynamically add additional properties to an object at runtime. Additionally, sorting and filtering capabilities may be desired.

Adding Dynamic Properties

To achieve this, a dictionary can be employed. For instance, the following code utilizes a dictionary to store the dynamic properties:

Dictionary<string, object> properties = new Dictionary<string, object>();

This allows for the dynamic addition of properties to the object using the square bracket syntax:

properties["propertyName"] = value;

Sorting and Filtering

To implement sorting and filtering, the example provided utilizes LINQ's Where and Select methods for filtering, and a custom comparer class for sorting. Here's an example:

// Example comparer class for sorting
public class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable
{
    string attributeName;

    public Comparer(string attributeName)
    {
        this.attributeName = attributeName;
    }

    public int Compare(ObjectWithProperties x, ObjectWithProperties y)
    {
        return ((T)x[attributeName]).CompareTo((T)y[attributeName]);
    }
}

// Example of filtering
var filteredObjects = from obj in objects
                 where (int)obj["propertyName"] >= 150
                 select obj;

// Example of sorting
Comparer<int> comparer = new Comparer<int>("propertyName");
objects.Sort(comparer);

By employing these techniques, dynamic properties can be added to an object at runtime, along with sorting and filtering capabilities.

The above is the detailed content of How to Add, Sort, and Filter Dynamic Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn