Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

Update a variable in list from another list using c# linq

I want to copy data from one list to another list. While copying to the new list, i want to assign new values also. Can someone please assist quickly. I want to achieve something like below,

public HashSet<string> MobileNumber { get; set; }        
var contactViewData = MobileNumber.Select(p => p).SelectMany(o => o.SplitFromCsv()).Select(x => new ContactViewMap()
{
     ContactId = Guid.NewGuid().ToString(),
     NewMobileNumber = x,
     OldMobileNumber = p
}).ToList();

public class ContactViewMap
{
    public string ContactId { get; set; }
    public string NewMobileNumber { get; set; }
    public string OldMobileNumber { get; set; }
}


public static IEnumerable<string> SplitFromCsv(this string csv)
            => csv.Split(',', StringSplitOptions.None);

Input:
{
  "MobileNumber": [
    "+9112352",
    "+9112353"
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Select(p => p) Just returns the same item again.

I think instead of this: Select(p => p).SelectMany(o => o.SplitFromCsv())
You need this: Select(p => (p, csv: o.SplitFromCsv()) )

Now you can use that tuple in the final Select:

.Select(x => new ContactViewMap()
{
     ContactId = Guid.NewGuid().ToString(),
     NewMobileNumber = x.csv,
     OldMobileNumber = x.p
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...