dynamically define key name for which the value needs to be identified

Viewed 35

I have a keyvalue pair list some thing like this

 List<Subscriptions> subs = new List<Subscriptions>();
subs.Add(new Subscriptions() { Id = 1, Name = "ABC" });
            subs.Add(new Subscriptions() { Id = 1, Name = "DEF" });

I can search against one key (ID or Name) but what I want to achieve is that user define which key they want to search against ID or Name

right now i am using this approach to filter the list based on Name Value

 var filtered = subs.Where(sub => sub.Name.IndexOf(SearchString.Text,StringComparison.OrdinalIgnoreCase) >=0);

sub.Name is defined statically here, I want the user to choose what they want their search to be based on

for example if we have abc:Name program search for abc under Name key and if we have 1:Id then it search for 1 in ID. This is just an example , in real scenario i can have multiple fields in my list. I hope I am able to make myself clear.

2 Answers

Why you don't apply the Where by an simple if else or switch

// keyword : abc:Name or  1:Id
var value = keyword.Split(':')[0];
var key = keyword.Split(':')[1];

if(key == "Name")
{
    var filterred = subs.Where(sub => sub.Name == value);
}
else if(key == "Id")
    var filterred = subs.Where(sub => sub.id == int.Parse(value));
}

Fast answer:

string name = "";
int? id = null;

List<Subscriptions> subs = new List<Subscriptions>();

var query = subs.AsQueryable();

if (!string.IsNullOrEmpty(name))
    query = query.Where(p => p.Name == name);

if (id.HasValue)
    query = query.Where(p => p.id == id.Value);

var result = query.ToArray();

Detailed answer: you can read about expression tree and IQueryable interface

Basically you can avoid to cast your list to IQueryable if you not use something like Entity Frmework or OData. But if you need to convert you LINQ expression to something more complex - you should use IQueryable, or build your own expression tree.

Related