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
Release: 2025-01-05 04:00:40
Original
484 people have browsed it

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>();
Copy after login

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

properties["propertyName"] = value;
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template