使用LINQ将所有元素连接在一个字符串中

时间:2015-08-03 12:33:02

标签: linq entity-framework

我有以下课程:

public class People 
{
    public int ID { get; set; }
    public List<Right> Rights { get; set; }
}

public class Right
{
    public int ID { get; set; }
    public int Val { get; set; }
}

使用以下值:

  • 人:身份证:1
    • 右:
      • ID:1
      • Val:5
    • 右:
      • ID:2
      • Val:4

我想为人们检索所有Val权利(在单个字符串中)。

对于ID为1的人:获取"5,4"

2 个答案:

答案 0 :(得分:2)

您可以使用SelectMany展平结构,例如:

var vals = people.Where(p => p.ID == 1)
                 .SelectMany(p => p.Rights.Select(r => Val));

var str = String.Join(",", vals.Select(v => v.ToString());

答案 1 :(得分:2)

List<People> list = ...;

string result = string.Join(",", (people.First(p => p.ID == 1)).Rights.Select(r => r.Val));

示例:

        List<People> people = new List<People>()
        {
            new People() 
            {
                ID = 1, Rights = new List<Right>()
                {
                    new Right() { ID = 1, Val = 5 }, 
                    new Right() { ID = 2, Val = 10 }, 
                }
            },

            new People() 
            {
                ID = 2, Rights = new List<Right>()
                {
                    new Right() { ID = 1, Val = 6 }, 
                    new Right() { ID = 2, Val = 11 }, 
                }
            }
        };

        string result = string.Join(",", (people.First(p => p.ID == 1)).Rights.Select(r => r.Val));

        Console.WriteLine(result);

输出:5, 10