2011-02-16 70 views
0

我已經問了這個問題(「轉換/ Casting ISingleResult - 列出值到我的班沒有循環」),但我沒有給出一個正確的例子。所以我重複着同樣的問題,以正確的示例:將ISingleResult列表值轉換爲我的班級沒有循環

我有這樣一個DataContract:

[Serializable] 
[DataContract] 
public class Employee 
{ 
    public Employee() 
    { 
    } 
    [DataMember] 
    public string Name { get; set; } 
    [DataMember] 
    public int EmpId { get; set; } 
    [DataMember] 
    public List<EmpMonthSal> EmpMonthlySal { get; set; } 
} 

public class EmpMonthSal 
{ 
    public EmpMonthSal() 
    { 

    } 

    [DataMember] 
    public int EmpId { get; set; } 
    [DataMember] 
    public int Month { get; set; } 
    [DataMember] 
    public float Sal { get; set; } 
} 

而且我使用LINQ我它創建下面的代碼C#應用程序到SQL:

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetEmployeeDetails" 
)]public ISingleResult<GetEmployeeDetailsResult> 
GetEmployeeDetails([global::System.Data.Linq.Mapping.ParameterAttribute(Name= 
"EmpId", DbType="NVarChar(32)")] string empID){IExecuteResult result = 
this.ExecuteMethodCall(this, ((MethodInfo) (MethodInfo.GetCurrentMethod())) 
, empID);return ((ISingleResult<GetEmployeeDetailsResult>)(result.ReturnValue)); 
} 

而產生GetEmployeeDetailsResult類汽車看起來是這樣的:

public class GetEmployeeDetailsResult 
{ 
    public GetEmployeeDetailsResult() 
    { 
    } 

    public string Name { get; set; } 
    public int EmpId { get; set; } 
    public int month { get; set; } 
    public float sal { get; set; } 
} 

我GetEmployeeDetailsResult的ISingleResult結果轉換到一個列表,我得到的東西是這樣的:

Empname EmpID  Month  Salary 

Raja 1 1 8000 

Raja 1 2 8000 

Raja 1 3 8000 

Raja 1 4 7800 

Raja 1 5 7800 

Raja 1 6 7800 

Raja 1 7 7800 

Raja 1 8 7800 

Raja 1 9 7800 

Raja 1 10 7800 

Raja 1 11 7800 

Raja 1 12 90000 

Kumar 2 1 200000 

Kumar 2 2 200000 

Kumar 2 3 200000 

Kumar 2 4 200000 

Kumar 2 5 200000 

Kumar 2 6 200000 

Kumar 2 7 200000 

Kumar 2 8 200000 

Kumar 2 9 195000 

Kumar 2 10 200000 

Kumar 2 11 198000 

Kumar 2 12 200000 

我想這個平面列表映射回Employee類的一個對象。我不想遍歷列表併爲每個類創建對象。

是否有任何其他方式像再次寫一個linq查詢或其他任何真的很聰明。

請給點建議。

+0

[轉換/鑄造ISingleResult - 列表值上我的課沒有循環。]的可能重複(HTTP://計算器.com/questions/4972198 /轉換鑄造-Isingleresult-list-values-to-my-class-without-looping) – jason 2011-02-16 18:52:19

+0

雖然有人在某個地方無疑會想到一些有能力的東西,但是它不會看起來太漂亮。 – 2011-02-16 18:54:14

回答

2

試試這個:

List<GetEmployeeDetailsResult> list; 

//填充您的列表莫名其妙

IEnumerable<Employee> result = list.GroupBy(e => new { id = e.EmpId, name = e.Name }) 
        .Select(e => new Employee 
        { 
         EmpId = e.Key.id, 
         Name = e.Key.name, 
         EmpMonthlySal = e.Select(ms => new EmpMonthSal 
         { 
          EmpId = e.Key.id, 
          Month = ms.month, 
          Sal = ms.sal 
         }).ToList() 
        });