使用LINQ交换列表值

时间:2015-12-21 11:45:38

标签: c# linq

我想交换列表,如下所述。我想保留列表的计数,其中一些元素值(不是全部)要从' primary'到中学'。

namespace listswap
{

    public class emp
    {
        public int id { get; set; }
        public string primary { get; set; }
        public string fName { get; set; }
        public string lName { get; set; }
        public string state { get; set; }
        public string country { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var empList = new List<emp>();
         empList.AddRange(new emp[] { new emp {primary = "Yes", id = 1, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"},
                                     new emp { primary = "No", id = 2, fName = "Deepak", lName = "Kumar", state = "AP", country = "UK"},

        });


            /* Desired list :    
            No of list 1 with two elements              
            empList[0]. primary = "Yes", id = 1, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"
            empList[1]. primary = "No", id = 2, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"

            */
        }
    }
}

1 个答案:

答案 0 :(得分:3)

这是基础知识,简单如下:

var l1 = empList.Where(c=>c.primary == "Yes").ToList();
var l2 = empList.Where(c=>c.primary == "No").ToList();

列表清单:

var result = empList.GroupBy(c => c.primary).Select(c => c.ToList()).ToList();

修改

var primary = empList.FirstOrDefault(c => c.primary == "Yes");

var r = empList.Select(c => new emp
{
    primary = c.primary,
    id = c.id,
    fName = primary != null ? primary.fName : c.fName,
    lName = primary != null ? primary.lName : c.lName,
    state = primary != null ? primary.state : c.state,
    country = primary != null ? primary.country : c.country
}).ToList();