使用Linq查询展平集合

时间:2017-06-28 23:12:18

标签: c# linq linq-to-sql

展平生成看起来像这样的集合的查询的最佳方法是什么?

enter image description here

而不是ClaimType Target的两行,我想生成一个linq查询或表达式,其中有一行用于ClaimType Target,同时列中包含Tools和Compass的值。

ClaimType | ClaimValue
Target    | Tools;Compass

任何想法,我都有这个全脑云!

2 个答案:

答案 0 :(得分:0)

由于我没有表格,我已创建对象列表来模拟您的数据,我希望这可能会有所帮助

 List<item> items = new List<item>();

            items.Add(new item { id = 1, name = "A", CliamId = "6", ClaimValue = "Any" });
            items.Add(new item { id = 1, name = "Target", CliamId = "8", ClaimValue = "Tools" });
            items.Add(new item { id = 1, name = "Target", CliamId = "9", ClaimValue = "Compass" });


            var query = from i in items
                        group i by i.name
                        into g
                        select g;

            foreach(var item in query)
            {
                Console.Write(string.Format("{0} ", item.Key));
                foreach(var row in item)
                {
                    Console.Write(string.Format("{0} ",row.ClaimValue));

                }
                Console.WriteLine();
            }


            Console.ReadLine();
        }



        // end of the class
    }

    class item
    {
        public int id { get; set; }
        public string name { get; set; }
        public string CliamId { get; set; }
        public string ClaimValue { get; set; }
        // end of the calss
    }

结果:

enter image description here

答案 1 :(得分:0)

我将如何做到这一点:

var claims = new []
{
    new { ClaimType = "Redirect Url", ClaimValue = "https://www.thing.com/" },
    new { ClaimType = "Target", ClaimValue = "Tools" },
    new { ClaimType = "Target", ClaimValue = "Compass" },
};

var query =
    from claim in claims
    group claim by claim.ClaimType into claim_groups
    select new
    {
        ClaimType = claim_groups.Key,
        ClaimValues = String.Join(";", claim_groups.Select(x => x.ClaimValue)),
    };

那会给你这个:

query