简体   繁体   中英

Compare list elements with string

I have a list of db table type I want to access list elements and compare with string but I cannot access list elements How to do it?

List<Tbl_UserCustomField> customattribute = (from custom in tniDataContext.Tbl_UserCustomFields 
                                             where workOrderIndex.LoginId == custom.LoginId 
                                             select custom).ToList();

After executing the query and storing the query result in list the customattribute is only returning count of elements in list but i want elements in string

Access it like:

foreach(var item in customattribute)
{
    if(item.SomeField == "someString")
       DoSomething();
    else
       DoSomethingElse();
}

If the varchar column is all you want then you can directly select it:

var customattribute = (from custom in tniDataContext.Tbl_UserCustomFields 
                       where workOrderIndex.LoginId == custom.LoginId 
                       select custom.SomeColumn).ToList();

foreach(var item in customattribute)
{
    if(item == "someString")
       DoSomething();
    else
       DoSomethingElse();
}

Try customattribute.ForEach(i => Console.Write("{0}\\t", i)); and see what is showing on console?

If you know the column or property in Tbl_UserCustomField class which holds the string you are looking for, iterate through the customattribute and fetch the string. Basically, you will have to capture such result in a variable of type List<string> . This can be done in a plain foreach-way OR using a Select Linq expression that just retrieves the column you specify

        // Approach 1:
        List<string> customAttributeValues = customattribute.Select(c => c.YourStringFieldName).ToList();

        // Approach 2:
        List<string> customAttributeValues = new List<string>();
        foreach (var custom in customattribute)
        {
            customAttributeValues.Add(custom.YourStringFieldName);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM