当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Querying a list of strings with a query string?

问题描述:

I have a dictionary:

<string,List<string>>

The key is the product code say "product1" then the list is a list of properties:

"Brand","10.40","64","red","S"

Then I 'can' have a list of rules/filters e.g.

var tmpFilter = new customfilters();

tmpFilter.Field = "2";

tmpFilter.Expression = ">";

tmpFilter.Filter = "10";

So for the above example this would pass because at index 2 (tmpFilter.Field) it is more than 10; then I have another object which defines which fields within the list I want to write to file. For that dictionary item I just want to write the product brand and price where the filters match.

At the moment without the filter I have:

var tmp = new custom();

tmp.Columns = "0,1";

tmp.Delimiter = ",";

tmp.Extention = ".csv";

tmp.CustomFilters = new List<customfilters>() {new customfilters(){ Field = "2", Expression = ">", Filter = "10"} };

public static void Custom(custom custom)

{

foreach (var x in Settings.Prods)

{

//Get Current Product Code

var curprod = Settings.ProductInformation[x];// the dictionary value

foreach (var column in custom.Columns)

{

var curVal = curprod[Convert.ToInt32(column)];

tsw.Write(curVal + custom.Delimiter);

}

Settings.Lines++;

tsw.WriteLine();

}

tsw.Close();

}

I only want to write the curprod if all the filters pass for that list of strings.

How I can do this?

网友答案:

There's a really nice Nuget package based on an example published by Microsoft, that they have decided to make really hard to find for some reason, that allows dynamic linq queries:

https://www.nuget.org/packages/System.Linq.Dynamic/1.0.2

Source:

https://github.com/kahanu/System.Linq.Dynamic

Using that you can do stuff like this very easily (note: I used strings here because the OP states they have a List<string>):

List<string> stuff = new List<string> { "10.40", "64", "5", "56", "99", "2" };

var selected = stuff.Select(s => new { d = double.Parse(s) }).Where("d > 10");

Console.WriteLine(string.Join(", ", selected.Select(s => s.d.ToString()).ToArray()));

Outputs:

10.4, 64, 56, 99

That may give you a place to start. One thing you are going to have to tackle is identifying which of your fields are numeric and should be converted to a numeric type before trying to apply your filter. Otherwise you are going to comparing as strings.

分享给朋友:
您可能感兴趣的文章:
随机阅读: