简体   繁体   中英

Select rows with LINQ from List<Dictionary<string, object>>

Lets assume simple data:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("obj 1", null);
dict.Add("obj 2", new object());
dict.Add("obj 3", new object());
dict.Add("obj 4", null);

Dictionary<string, object> dict2 = new Dictionary<string, object>();
dict2.Add("obj 1", null);
dict2.Add("obj 2", new object());
dict2.Add("obj 3", null);
dict2.Add("obj 4", null);

Dictionary<string, object> dict3 = new Dictionary<string, object>();
dict3.Add("obj 1", null);
dict3.Add("obj 2", null);
dict3.Add("obj 3", new object());
dict3.Add("obj 4", null);

List<Dictionary<string, object>> list = new List<Dictionary<string, object>> {dict, dict2, dict3};

Is it possible select rows and remove key/value where in all columns are null? So after this in my list will be:

dict({"obj 2", object}, {"obj 3", object})
dict2({"obj 2", object}, {"obj 3", null})
dict2({"obj 2", null}, {"obj 3", object})

try this:

 list.ForEach(x =>
        {

            x.Where(y => y.Value == null).ToList().ForEach(z=>
                {
                    if(list.All(l=>!l.ContainsKey(z.Key)|| l[z.Key]==null))
                        x.Remove(z.Key);
                });
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM