JHah
JHah

Reputation: 486

LINQ query as parameter in function C#

I have an enum say EnumA with values X, Y, Z, P, Q R I have created a function called Sort(linqquery as parameter) in C#, .NET version 4.7.2

I should be able to write a function parameter something like

tt=>tt.X.Ascending().ThenBy(tt.Y).ThenBy(tt.P.Descending())

The function body will sort the returning result by A ascending then by Y and then P Descending.

It is only one example of I want to achieve.

Another Example:

RemoveColumn ( LINQquery as parameter)

    tt=>tt.X && tt.Y && tt.Q

[{  "X": "Name",  "Y": "Hello",  "Z": 10,  "P": "Some value",  "Q": " Hello Again",  "R": "my data"}, {  "X": " Ha ha ha ",   "Y": "by bye",   "Z": 100,   "P": " value",   "Q": " Again",   "R": "m data"},{   "X": " Your Name",   "Y": "why",   "Z": 9,   "P": "  Ok  Some value",   "Q": " Music",   "R": " atda" }, {   "X": "John",   "Y": "Nuew",   "Z": 10,   "P": "Why your  value",   "Q": " Ta ta ata Again",   "R": "  cycle" }]

Above is my sample JSON also. Based on linq parameter i will filter or sort this JSOn before being returned by the function. How do I be able to pass LINQ as parameter?

Upvotes: 0

Views: 326

Answers (1)

Enigmativity
Enigmativity

Reputation: 117029

From the sounds of it you basically need to do this:

Func<IEnumerable<Data>, IEnumerable<Data>> transform =
    tt => tt.OrderBy(t => t.X).ThenBy(t => t.Y).ThenByDescending(t => t.P);

Func<Data, bool> predicate =
    t => t.X == "John" && t.Y == "Nuew" && t.Q == " Ta ta ata Again";

You'd start with the class Data:

public class Data
{
    public string X;
    public string Y;
    public int Z;
    public string P;
    public string Q;
    public string R;
}

Then read it in like this:

IEnumerable<Data> data1 = JsonConvert.DeserializeObject<Data[]>(File.ReadAllText("file.json"));

And then call the following:

IEnumerable<Data> data2 = transform(data1);

IEnumerable<Data> data3 = data2.Where(predicate);

That'll give you this:

datas

Upvotes: 1

Related Questions