Search code examples
c#wpfentity-frameworklinqdatacontext

Pass query result to method (Linq, Wpf)


I have method to save all values from table to txt file:

        UserDataDBsDataContext dataContext = new UserDataDBsDataContext();
        List<UserData> usersL = (from u in dataContext.UserDatas
                                 select u).ToList();

        var properties = typeof(UserData).GetProperties();
        var userValues = new List<string>();

        foreach (var user in usersL)
        {
            var values = new List<object>();
            foreach (var property in properties)
            {
                object value = property.GetValue(user, null);
                values.Add(value);
            }
            userValues.Add(string.Join(",", values));
        }
        File.WriteAllLines("my_data.txt", userValues);

Now I have two query and I want to do exactly the same, so I tried to create separate method responsible for looping table values.

Loop Method:

    public void loopProp(PropertyInfo[] properites, List<string> addedValues)
    {           
        foreach (var qrl in ...........)
        {
            var values = new List<object>();
            foreach (var property in properites)
            {
                object value = property.GetValue(qrl, null);
                values.Add(value);
            }
            addedValues.Add(string.Join(",", values));
        }
        File.WriteAllLines("my_passed_data.txt", addedValues);
    }

But I don't know, how to pass query result(ar or ud):

My code:

List<AutoRef> ar = (from a in rjdc.AutoRefs
                    select a).ToList();
List<UserDataRef> ud = (from u in rjdc.UserDataRefs
                       select u).ToList();

            var propertiesAutoRef = typeof(AutoRef).GetProperties();
            var autoValues = new List<string>();

            var propertiesUserRef = typeof(UserDataRef).GetProperties();
            var userValues = new List<string>();

            //loopProp(propertiesAutoRef, autoValues);
            //loopProp(propertiesUserRef, userValues);

Solution

  • Answering your concrete question. You should make the method generic and pass the source as IEnumerable<T>:

    public void loopProp<T>(IEnumerable<T> source, PropertyInfo[] properites, List<string> addedValues)
    {           
        foreach (var qrl in source)
        {
            // ...
        }
        File.WriteAllLines("my_passed_data.txt", addedValues);
    }
    

    Usage:

    loopProp(ar, propertiesAutoRef, autoValues);
    loopProp(ud, propertiesUserRef, userValues);
    

    Probably you should pass the file path argument as well instead of hardcoding it inside the method.