C# 使用LINQ交换列表值
我想交换列表,如下所述。我想保留一些元素值(不是全部)的列表计数,这些值将从“主要”交换到“次要”C# 使用LINQ交换列表值,c#,linq,C#,Linq,我想交换列表,如下所述。我想保留一些元素值(不是全部)的列表计数,这些值将从“主要”交换到“次要” namespace listswap { public class emp { public int id { get; set; } public string primary { get; set; } public string fName { get; set; } public string lName {
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"
*/
}
}
}
名称空间列表交换
{
公共级电磁脉冲
{
公共int id{get;set;}
公共字符串主{get;set;}
公共字符串fName{get;set;}
公共字符串lName{get;set;}
公共字符串状态{get;set;}
公共字符串国家{get;set;}
}
班级计划
{
静态void Main(字符串[]参数)
{
var empList=新列表();
empList.AddRange(new emp[]{new emp{primary=“Yes”,id=1,fName=“Vivek”,lName=“Ranjan”,state=“TN”,country=“India”},
新的emp{primary=“No”,id=2,fName=“Deepak”,lName=“Kumar”,state=“AP”,country=“UK”},
});
/*所需列表:
包含两个元素的列表1的编号
雇员列表[0]。primary=“Yes”,id=1,fName=“Vivek”,lName=“Ranjan”,state=“TN”,country=“India”
雇员列表[1]。primary=“No”,id=2,fName=“Vivek”,lName=“Ranjan”,state=“TN”,country=“India”
*/
}
}
}
这是最基本的,非常简单:
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();
应该有一个列表和两个列表element@GirishKumar,如果您的意思是一个列表列表和两个列表,请参见更改。另一方面,这个问题对我来说毫无意义,因为你已经有了一个包含2个元素的列表…我的愿望列表是元素0。primary=“Yes”,id=1,fName=“Vivek”,lName=“Ranjan”,state=“TN”,country=“India”元素1。primary=“No”,id=2,fName=“Vivek”,lName=“Ranjan”,state=“TN”,country=“India”你的成绩和我不一样excpecting@GirishKumar,我找不到您-您已在员工列表中获得所需的结果。。。你能详细说明一下吗?