使用LINQ交换列表值

本文关键字:列表 交换 LINQ 使用 | 更新日期: 2023-09-27 18:27:38

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

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"
            */
        }
    }
}

使用LINQ交换列表值

这是基本的,简单到:

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