2015-12-21 39 views
-2

我想按照下面的說明交換列表。我想保留一些元素值(不是全部)從「主」換到「次」的列表數。使用LINQ交換列表值

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" 

      */ 
     } 
    } 
} 

回答

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

應該有一個列表empList用兩個元素 –

+0

@GirishKumar,如果你的意思是'一個列表empList有兩個列表'然後看到變化。其他方式的問題對我來說沒有意義,因爲你已經有一個包含2個元素的列表... –

+0

我的願望列表是 元素0. primary =「Yes」,id = 1,fName =「Vivek」,lName =「Ranjan 「state =」TN「,country =」India「 element 1. primary =」No「,id = 2,fName =」Vivek「,lName =」Ranjan「,state =」TN「,country =」India「 –