将查询结果传递给方法(Linq,Wpf)

时间:2017-04-06 07:31:15

标签: c# wpf entity-framework linq datacontext

我有方法将所有值从表保存到txt文件:

        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);

现在我有两个查询,我想完全相同,所以我尝试创建负责循环表值的单独方法。

循环方法:

    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);
    }

但是我不知道如何传递查询结果( ar ud ):

我的代码

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);

1 个答案:

答案 0 :(得分:2)

回答你的具体问题。您应该使方法通用并将源传递为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);
}

用法:

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

可能你也应该传递文件路径参数,而不是在方法中硬编码。