How to cast a List<T> object into Text - c#

I want to know if I can access an item of my List and assign it to a textbox?
public static List<Product> detailsList = new List<Product>();
Product is my class generated by using LINQ to SQL with fields Name,Code,Details i.e my List contains the items(Name,Code,Details). I want to access the value of the item Details from the list and assign it to a textbox . Something like:
txtDetails.Text = detailsList.Details.ToString()

If you want the details of 1 item:
var detailsList = new List<TaskDto>();
// add items
// this if you know the corect index
txtDetails.Text = detailsList[0].Details;
// if you need to query for example for the item with the correct Id
txtDetails.Text = detailsList.FirstOrDefault(p => p.Id == 1).Details;

You can select first or default from the item based on some criteria, like the name.
public static List<Product> detailsList = new List<Product>();
var prod = detailsList.FirstOrDefault(p => p.Name == 'Ana');
if(prod != null) {
txtDetails.Text = prod.Details;
}

For all items:
var joinSymbol = ", ";
txtDetails.Text = string.Join(joinSymbol, detailsList.Select(detail => detail.Details));
For first item if Details:
txtDetails.Text = detailsList.FirstOrDefault()?.Details ?? string.Empty;

use string.Join() function.
txtDetails.Text = string.Join(",", detailsList.Select(e => e.Details)).ToList());

Related

How to separate values by ";" in foreach loop for each item using C#

I have a foreach loop iterating each item at a time, I want to separate each item by using ";"
But not adding ";" for the last item.
I have tried using String.Join(";", item), But it did not work for me.
I get the output as : SN-123SN-456SN-789
Output should look something like this: SN-123;SN-456;SN-789
Please find my code below:
if (siteId != "null")
{
var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
List<string> siteSNlist = siteList.Gateways.Select(x => x.SerialNumber).ToList();
foreach (var item in siteSNlist)
{
siteSN += String.Join(";", item);
}
}
You need to use string join for a collection, try like this:
if (siteId != "null")
{
var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
List<string> siteSNlist = siteList.Gateways.Select(x => x.SerialNumber).ToList();
siteSN = String.Join(";", siteSNlist);
}
For the nested objects you can use select:
if (partnerId != "null")
{
var partnerList = this.feeDataAccess.GetPartnerListbyId(connectedUser.CurrentEnvironment, partnerId);
foreach (var item in partnerList)
{
var partnerSN = string.Join(";", item.Gateways.Select(x => x.SerialNumber));
}
}
String.Join can Concatenates the members of a constructed System.Collections.Generic.IEnumerable`1 collection of type System.String, using the specified separator between each member. So we can use list directly in Join.
List<string> siteSNlist = new List<string>() { "SN-123", "SN-124", "SN-125" , "SN-126"};
string siteSN = string.Join(";", siteSNlist);
Output : SN-123;SN-124;SN-125;SN-126

Can I merge these two lists in 1 go

What I am trying to do,
// get members from SharePoint list (can be null)
// get members from database (can be null)
// merge database members with sharepoint list members BUT only database members should have property VIP = true
// by merge I mean if they are not in list then add them to list, if they are in list then just change there property VIP = true
// by default VIP property is false
What I have developed so far,
List<Member> Members = new List<Member>();
foreach (SPListItem mItem in GetList(Url).Items)
{
Member m = new Member();
m.ID = mItem.ID;
m.Name = mItem.Title;
m.Company = Utilities.ObjectToStringOrEmpty(mItem[companyCol]);
m.eMail = Utilities.ObjectToStringOrEmpty(mItem[emailCol]);
m.Comment = Utilities.ObjectToStringOrEmpty(mItem[commentCol]);
m.Membership = Utilities.ObjectToStringOrEmpty(mItem[msCol]);
Members.Add(m);
}
var cd = new MemberManager().GetMoreMembers(Url + "/");
var activeMembers = cd.Where(am => am.MembershipStatus == "Active" || am.MembershipStatus == "Pending").ToList();
if (activeMembers != null || activeMembers.Count() > 0)
{
foreach (var am in activeMembers)
{
if (!Members.Any(a => a.eMail.ToLowerInvariant() == am.Email.ToLowerInvariant()))
{
Member m = new Member();
m.Name = am.FirstName + " " + am.LastName;
m.eMail = am.Email;
m.IsVip = true;
Members.Add(m);
}
}
}
md.Members = Members.ToArray();
Problem
Can I use Linq and merge these lists in a single go ? Maybe something like this, pseudo would be
var dbMembers = //GetDBMembers that are active or pending
var spMembers =
Select all members using `.Cast<SPListItem>()`
If spMembers has any dbMember (compared by email)
Then change that spMembers VIP property to true (which is by default false)
For rest dbMembers that doesn't exists in spMembers, add them with VIP property = true
Not sure how can i efficiently put above pseudo code into linq
Try this:
var allSpMembers = GetSpList(); // get your members as you mentioned before by `.Cast<SPListItem>()`
List<SPListItem> spMembers =
dbMembers.GroupJoin(allSpMembers, dbM => dbM.Email, spM => spM.Email,
(dbMember, spMember) => new { dbMember, spMember })
.SelectMany(x => x.spMember.DefaultIfEmpty(), (x, spMember) =>
{
SPListItem yourSpListItem;
if (spMember != null)
{
yourSpListItem = spMember;
}
else
{
yourSpListItem = x.dbMember; //make some mapping here to SPListItem model
}
yourSpListItem.VIP = true;
return yourSpListItem;
}).ToList();
Yes you can. Use the Enumerable.Concat method to concatenate two lists into one.
If you split out the code to create Member objects into two methods, one MemberFromSpListItem and one MemberFromActiveMember then you will get the following relatively nice code:
var cd = new MemberManager().GetMoreMembers(Url + "/");
var activeMembers = cd.Where(am => am.MembershipStatus == "Active" || am.MembershipStatus == "Pending").ToList();
var members = GetList(Url)
.Items
.Select(MemberFromSpListItem)
.Concat(activeMembers.Select(MemberFromActiveMember))
.ToList();

Merge Rows in List. if one column has different values

I am using the below logic to merge List rows in a list together if they have all have identical columns apart from one (OtherAuditeesUserName). In which case i join the different values of OtherAuditeesUserName with a comma seperater
The original list looks like this:
TrailRemarkId,PreviousAudit,OtherAuditees,StrategicPriority,Observations,DocumentsReviewed
1,"old audit","jane smith", 1,none, doc.docx
1,"old audit","john collins", 1,none, doc.docx
The end result I am looking for is :
TrailRemarkId,PreviousAudit,OtherAuditees,StrategicPriority,Observations,DocumentsReviewed
1,"old audit","jane smaith, john collins", 1,none, doc.docx
see how OtherAuditees is joined using a comma.
Can someone point out a more efficient way to merge List rows ?
var trailRemarks = (from a in auditData
select new
{
a.TrailRemarkId,
a.PreviousAudit,
a.OtherAuditees,
a.StrategicPriority,
a.Observations,
a.DocumentsReviewed,
}).Distinct();
List<TrailRemarkEntity> trlist = new List<TrailRemarkEntity>() ;
int? trId = 0;
foreach (var tr in trailRemarks)
{
if (trId == 0 || (trId != tr.TrailRemarkId))
{
trlist.Add(
new TrailRemarkEntity()
{
TrailRemarkId = tr.TrailRemarkId ?? 0,
PreviousAuditName = tr.PreviousAudit,
DocumentsReviewed = tr.DocumentsReviewed,
StrategicPriorityName = tr.StrategicPriority,
OtherAuditeesUserName = tr.OtherAuditees,
Observations = tr.Observations
}
);
}
else
{
var existingTR = trlist.Last();
existingTR.OtherAuditeesUserName += ", " + tr.OtherAuditees;
}
trId = tr.TrailRemarkId;
}
You can use group by and string.join for doing it like below,
List<TrailRemarkEntity> trailRemarks = (from a in auditData
group a by new {
a.TrailRemarkId,
a.TrailRemarkId,
a.PreviousAudit,
a.StrategicPriority,
a.Observations,
a.DocumentsReviewed
} into groupedData
select new TrailRemarkEntity()
{
TrailRemarkId = groupedData.Key.TrailRemarkId ?? 0,
PreviousAuditName = groupedData.Key.PreviousAudit,
DocumentsReviewed = groupedData.Key.DocumentsReviewed,
StrategicPriorityName = groupedData.Key.StrategicPriority,
OtherAuditeesUserName = string.join("," , groupedData.Select(exp=>exp.OtherAuditees)),
Observations = groupedData.Key.Observations
}).ToList();
Hope it helps.
Thanks thisiva, your solution worked but I modified it slightly to remove duplicates as follows:
string.Join(",", groupedData.Select(exp => exp.OtherAuditees).Distinct())

querying existing ListView items with LINQ

The ListView I have populates through these loops resulting in four columns being filled
// Create a ResXResourceReader
ResXResourceReader rdr0 = new ResXResourceReader(textPath1.Text + ".resx");
ResXResourceReader rdr1 = new ResXResourceReader(textPath1.Text + ".es.resx");
ResXResourceReader rdr2 = new ResXResourceReader(textPath1.Text + ".fr.resx");
foreach (DictionaryEntry d in rdr0)
{
TransResource x = new TransResource();
x.id = d.Key.ToString();
x.en = d.Value.ToString();
resources.Add(x.id, x);
}
foreach (DictionaryEntry d in rdr1)
{
TransResource x = resources[d.Key.ToString()];
x.fr = d.Value.ToString();
}
foreach (DictionaryEntry d in rdr2)
{
TransResource x = resources[d.Key.ToString()];
x.es = d.Value.ToString();
}
foreach (TransResource x in resources.Values)
{
string[] row = { x.id, x.en, x.fr, x.es };
var listViewItem = new ListViewItem(row);
listResx.Items.Add(listViewItem);
}
What I want to do is query all of the results in this ListView against what is entered in textboxQuery. If any field in the entire listview contains the string from textboxQuery I want it to be displayed in a new listview (lets say listviewQueryresult). I've had many failed attempts at this but I know it is possible through LINQ.
Because ListView.Items implements IEnumerable, but does not implement IEnumerable<T> you have to cast it to IEnumerable<ListViewItem> first, to query it using LINQ to Objects:
var results = listResx.Items.Cast<ListViewItem>()
.Where(x => YourPredicate(x));
If any field in the entire listview contains the string from
textboxQuery I want it to then be displayed in a new listview (lets
say listviewQueryresult)
For that, the predicate would be just:
var results = listResx.Items.Cast<ListViewItem>()
.Where(x => x.Text.Contains(textboxQuery));

Populating textboxes using LINQ2SQL

In my web forms, I have text boxes and one radiolist which I need to populate through a LINQ2SQL query. So far I coded this query to fetch particular records which is going to be populated into the DB.
using (dbTestDataContext db = new dbTestDataContext())
{
var query = from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
};
};
Now I know that the record which this query is going to be fetching is gonna be only 1 unique record. I want to show the record in these textboxes and select that radio button:
tbName
tbNum
tbAcctNum
rbtnCorpAcct
How should I do this? Thank you in advance!
Very simply:
using (dbTestDataContext db = new dbTestDataContext())
{
var query = (from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}).FirstOrDefault();
if (query != null)
{
tbName.Text = query.Name;
tbNum.Text = query.Num;
//and so on
rbl.SelectedValue = query.SomeValue;
}
};
Same as others have answered with addition of radio button:
tbName.Text = query.Name;
tbNum.Text = query.Num;
tbAcctNum.Text = query.AcctNum;
if(query.CorpAcct)
rbtn.SelectedValue = "Yes"; \\Where "Yes" is one of the radio button values
else
rbtn.SelectedValue = "No";
\\Could also use SelectedIndex, rbtn.SelectedIndex = 0 or 1
Try the following:
using (dbTestDataContext db = new dbTestDataContext())
{
var query =
(
from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}
).FirstOrDefault();
tbName.Text = query.Name;
....
};
The first thing you need to do is retrieve a single result from your query. As you have it written, you are returning an IQueryable object which is now stored in the variable "query"
To get a single object, do this
var myObject = query.SingleOrDefault();
Then you can access the individual properties of that object and assign them like this
tbName.Text = myObject.Name

Categories

Resources