Home > database >  linq where condition matched then create a new record using profile information in c#?
linq where condition matched then create a new record using profile information in c#?

Time:07-14

Need to create a new list for the below list.

if UniqueID= "10345" then i need to create new record like this { rowno = 3, sid = 12, snmae = Mark ,isDataFromProfile = 1} means that need to use ProfileName, ProfileID , ProfileAge

Output based on below

My expected output is

{ rowno = 1, sid = 1000, snmae = John }
{ rowno = 2, sid = 3090, snmae = Steve }
{ rowno = 3, sid = 5090, snmae = Ron }
{ rowno = 4, sid = 4300, snmae = Bill }
{ rowno = 5, sid = 5640, snmae = Ram }
{ rowno = 6, sid = 90, snmae = Gony }
{ rowno = 3, sid = 12, snmae = Mark ,isDataFromProfile = 1}
{ rowno = 6, sid = 1987, snmae = Antony ,isDataFromProfile = 1}

class:

public class Student{
    public string UniqueID{ get; set; }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
    public int StandardID { get; set; } 
    public string ProfileName{ get; set; }
    public string ProfileID{ get; set; }
    public string ProfileAge{ get; set; }
}

int counter = 1; 
var sdata = studentList.Select(i => new {rowno = counter  , sid = i.StudentID, snmae = i.StudentName }).ToList();       

CodePudding user response:

I think this is what you are looking for?
Select has an overload that handles indexes.

var sdata = studentList.Select((Value, Index) => new { Value, Index })
    .Select(x => new { rowno = x.Index, sid = x.Value.StudentID, snmae = x.Value.StudentName, isDataFromProfile = x.Value.UniqueID == "10345" ? 1 : 0 })
    .ToList();

Edited answer

var sdata = studentList.Select((Value, Index) => new { Value, Index })
    .Select(x => new { rowno = x.Index, sid = x.Value.StudentID, snmae = x.Value.StudentName, isDataFromProfile = 0 })
    .ToList();

var otherData = studentList.Select((Value, Index) => new { Value, Index })
    .Where(x => x.Value.UniqueID == "10345")
    .Select(x => new { rowno = x.Index, sid = Convert.ToInt32(x.Value.ProfileID), snmae = x.Value.ProfileName, isDataFromProfile = 1 })
    .ToList();

sdata.AddRange(otherData);
  • Related