Luka Pivk
Luka Pivk

Reputation: 466

Create and pass IEnumerable to method in one line

i have this few lines of code

FilterCondition CustomerID = new FilterCondition("Customer_ID",cust.Customer_ID,FilterCondition.FilterOperator.Equals);
        List<FilterCondition> conditions = new List<FilterCondition>();
        conditions.Add(CustomerID);
        conditions.Add(Location_is_last_used);
        Location loct = Store.Select<Location>(conditions).First();

I tried to make it work like this

Store.Count<Customer>(new List<FilterCondition>().Add(new FilterCondition("Customer_name",name,FilterCondition.FilterOperator.Equals))

But this wont work because Add returns void and its running me crazy, is there any other way to solve this in one line? i realy dont want to write conditions for everything that i need.

Tnx for help! Regards, Luka

Upvotes: 2

Views: 296

Answers (4)

Tigran
Tigran

Reputation: 62265

First of wall, I wouldn't do that, cause the code already good one, but if you really want to do that, one of possible pseudocode could be:

Location loct = Store.Select<Location>(new List<FilterCondition>{
           new FilterCondition{value = CustomerID}, 
            new FilterCondition{value = Location_is_last_used}
}).First();

Should work for you.

Repeat, in my opinion, your code is a way better. It's easier to read.

Upvotes: 0

O. R. Mapper
O. R. Mapper

Reputation: 20770

You could write an extension method:

public static class MyExtensions
{
    public static ICollection<T> AddChainable<T>(this ICollection<T> collection, T newItem)
    {
        collection.Add(newItem);
        return collection;
    }
}

You could then invoke this as follows:

Store.Count<Customer>(new List<FilterCondition>().AddChainable(new FilterCondition("Customer_name",name,FilterCondition.FilterOperator.Equals));

(assuming Store.Count<T> works on ICollection<T>, which introduces the Count property, otherwise adapt the collection type appropriately.

The advantage over the list initializer syntax is that you could use this also for already created list objects (e.g. if you get the list object from a factory method).

Upvotes: 1

Ribtoks
Ribtoks

Reputation: 6922

You can use

new List<FilterConditions>() { new FilterCondition("Customer_name",name,FilterCondition.FilterOperator.Equals) }

as List initializer

Upvotes: 0

Kek
Kek

Reputation: 3195

Store.Count<Customer>(new FilterCondition[]{new FilterCondition("Customer_name",name,FilterCondition.FilterOperator.Equals)}.ToList())

Upvotes: 0

Related Questions