Find all objects in List<T> with same property value - search

I have a class Card, which has property Rank (1,2,3 etc) and I have a list of Cards and I wish to find all the Cards with the same Rank value in that list.
The list of Cards is sorted by Rank beforehand.
What would be the fasted way in .NET (using LINQ, if possible) to find all the objects with the same property value.
I don't know what the property value is beforehand, so I have to go through and compare. Until now I've been looping and keeping references to previous objects to compare, but I was wondering if there is not some easier way to do this?
Point is I need to be able to find N elements in a list with the same property value.
There might not be, but I thought I'd still ask.

You could group the cards by rank:
public class Card
{
public int Rank { get; set; }
}
class Program
{
static void Main()
{
var cards = new[]
{
new Card { Rank = 1 },
new Card { Rank = 2 },
new Card { Rank = 3 },
new Card { Rank = 2 },
new Card { Rank = 1 },
};
var groups = cards.GroupBy(x => x.Rank);
foreach (var group in groups)
{
Console.WriteLine("Cards with rank {0}", group.Key);
foreach (var card in group)
{
Console.WriteLine(card.Rank);
}
}
}
}

easiest would be to use linq
var results = myCardList.Select( c=>c.rank == myRank );
then you can iterate or convert to list.

Use Enumerable.ToLookup. The cards does not have to be sorted beforehand.
If you have a class
public class Card
{
public string Name { get; set; }
public int Rank { get; set; }
}
Then you can create a Lookup that groups per Rank like this
var cards = new Card[]{
new Card{Rank = 1, Name = "A"},
new Card{Rank = 1, Name = "B"},
new Card{Rank = 2, Name = "C"},
new Card{Rank = 3, Name = "D"},
};
var cardsByRank = cards.ToLookup(card => card.Rank);
foreach (var cardRankGroup in cardsByRank)
{
Console.WriteLine("KEY: " + cardRankGroup.Key);
foreach (var card in cardRankGroup)
{
Console.WriteLine(" Card: " + card.Name);
}
}
with the output
KEY: 1
Card: A
Card: B
KEY: 2
Card: C
KEY: 3
Card: D
Edit
if you want to extract all cards for a given Rank you can use rank as index to the lookup
foreach (var card in cardsByRank[2])
{
Console.WriteLine(" Card: " + card.Name);
}

Hey Tony, are you looking for something link this?
List<Card> rankedCards = cards.Where(o=> o.Rank == rank).ToList()
This should return a list of Cards that match the variable "rank" which I assume contains an int containing the value of Rank you want to match.

Related

Bug in OrmLite - updating record with Primary Key = 0

Given a simple poco
public class Model
{
[PrimaryKey]
public int ID { get; set; }
public string Description { get; set; }
}
this works fine ...
var connectionString = #"Data Source=WIN8PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True;";
connectionFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
using (var db = connectionFactory.OpenDbConnection())
{ db.DropAndCreateTable<Model>(); }
var model0 = new Model { ID = 0, Description = "Item Zero" };
var model1 = new Model { ID = 1, Description = "Item One" };
using (var db = connectionFactory.OpenDbConnection())
{ db.Save(model0, model1); }
as does this ...
model0.Description += " updated";
model1.Description += " updated";
using (var db = connectionFactory.OpenDbConnection())
{
db.Save(model0);
db.Save(model1);
}
however, this crashes with a primary key violation exception ...
model0.Description += " updated again";
model1.Description += " updated again";
using (var db = connectionFactory.OpenDbConnection())
{ db.Save(model0, model1); }
The record with ID zero is required, as this is a lookup table to replace an existing C# enum type. This is a local copy of distributed data (that I don't control), so there's no reason to have an auto-increment key.
The issue appears to be in OrmLiteWriteCommandExtensions.SaveAll() - any row with id == defaultValue is assumed to be a new item, rather than an update of an existing record. The same issue occurs in the parallel async methods too.
Is there any other way to get around this issue, other than by saving each record individually (inside a transaction). It would be preferable to save all updated records for a table in one command.
Save is a high-level API that will INSERT or UPDATE based on whether or not the Primary Key has a value. If you want to insert a default Primary Key value you can use Insert instead as seen in this Live Example on Gistlyn:
public class Model
{
[PrimaryKey]
public int ID { get; set; }
public string Description { get; set; }
}
db.DropAndCreateTable<Model>();
var model0 = new Model { ID = 0, Description = "Item Zero" };
var model1 = new Model { ID = 1, Description = "Item One" };
db.Insert(model0, model1);
var rows = db.Select<Model>();
"Inserted Rows: {0}".Print(rows.Dump());
Which outputs:
Inserted Rows: [
{
ID: 0,
Description: Item Zero
},
{
ID: 1,
Description: Item One
}
]

converting strings within Entity Framework query

The following query works perfectly fine and populates its dropdown list. The data in the data base is stored in all uppercase, ie PALM BEACH. I want to convert it to Proper case, which obviously i can do after the fact by iterating through the returned list and reformatting BUT I should be able to do it with in the query itself. The following query works fine.
Dim citylist As List(Of String) = (From c In ctx.ziptaxes
Where c.StateID = ddlStates.SelectedIndex
Order By c.City Ascending
Select c.City).ToList()
But if i try to convert it to some thing like this, it fails
Dim citylist As List(Of String) = (From c In ctx.ziptaxes
Where c.StateID = ddlStates.SelectedIndex
Let cityname = StrConv(c.City, VbStrConv.ProperCase)
Order By cityname Ascending
Select cityname).ToList()
I've tried using culture info and String.Format(c.City, vbProperCase) too and nothing other than the original query works. Any help appreciated.
ADDENDUM:
Well some further research is telling me that .Net objects like string conversion and cultureinfo cannot be used prior to the query being run. If that's the case it explains why it isn't working. The following solves my problem BUT I would still like to know if there is way to do it within the LINQ to EF.
Dim citylist As List(Of String) = (From c In ctx.ziptaxes
Where c.StateID = ddlStates.SelectedIndex
Order By c.City Ascending
Select c.City).ToList()
If citylist.Count > 0 Then
For i As Integer = 0 To citylist.Count - 1
citylist(i) = StrConv(citylist(i).ToLower(), vbProperCase)
Next
With ddlCity
.Items.Clear()
.DataSource = citylist.Distinct()
.DataBind()
.Items.Insert(0, "Select a city")
.SelectedIndex = 0
End With
End If
You can do the conversion in your SELECT. Here's an example (with an over-simplified City name converter):
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace LinqQuestion
{
[TestFixture]
public class StackOverflowTests
{
private IEnumerable<City> _cities;
[TestFixtureSetUp]
public void Arrange()
{
_cities = new List<City>
{
new City { Id = 1, Name = "FLINT", StateId = 1 },
new City { Id = 2, Name = "SAGINAW", StateId = 1 },
new City { Id = 3, Name = "DETROIT", StateId = 1 },
new City { Id = 4, Name = "FLint", StateId = 1 }
};
}
[Test]
public void TestCountryQuery()
{
var data = _cities
.Where(c => c.StateId == 1)
.OrderBy(c => c.Name)
.Select(c => StrConv(c.Name))
.Distinct().ToList();
Assert.That(data.Count == 3);
}
private static string StrConv(string original)
{
var firstLetter = original.Substring(0, 1).ToUpper();
var theRest = original.Substring(1, original.Length - 1).ToLower();
return firstLetter + theRest;
}
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string Name { get; set; }
}
}

Sequence Number for Id

I want to configure my Mongo DB to create sequence number for an Id column. Ex. It has to start from 1001 and increase by 1 automatically when I insert next row. I have my schema definitions as part of Node.JS how to add this configuration in Node schema?
MongoDB doesn't support this out of the box. The way I've implemented this (albeit in C#) is to create a "Sequence" collection with a key and a next number. You can atomically increment and return the next number then use this as the id in your collection.
This is a C# function, using the findandmodify mongodb command to fetch and update a sequence number for a given "key".
public long GetNextSequenceNumber(string name, string key)
{
var update = new BsonDocument(new BsonElement("$inc", new BsonDocument(new BsonElement("SequenceNumber", 1))));
var query = new BsonDocument("_id", key);
var command = new CommandDocument {
{ "findandmodify" , name },
{ "query", query},
{ "update" , update},
{ "new" , true},
};
var res = Db.RunCommand(command);
if (res.Response["value"] != BsonNull.Value)
{
var o = BsonSerializer.Deserialize<Sequence>(res.Response["value"].ToBsonDocument());
return o.SequenceNumber;
}
else
{
var o = new Sequence() { Id = key, SequenceNumber = 0 };
Db.GetCollection(name).Insert<Sequence>(o);
return o.SequenceNumber;
}
}
and the Sequence model:
public class Sequence
{
public string Id { get; set; }
public long SequenceNumber { get; set; }
}
The sequence documents look like:
{
_id : 'mykey',
SequenceNumber : NumberLong(1234)
}
If you need converting it to javascript please ask.
Hope that helps.

How to search in a Arraylist

I created an arraylist of Student type. Student has name, subject information in it. Suppose my ArrayList has values like (sam, maths), (john, english), (mat, science). If i want to find out which student has science stream, then how to search it in an ArrayList.
I think it may be done by using binarysearch or indexof methods, but not getting it right.
Why did you created an arraylist of Student type ?
I'm pretty sure that you should go with a generic type-safe list : List<T>
To do your searches you could use LINQ :
List<Student> students = new List<Student>();
students.Add(new Student { Lastname = "Smith" });
students.Add(new Student { Lastname = "Foo" });
students.Add(new Student { Lastname = "SmithFoo" });
students.Add(new Student { Lastname = "SmithBar" });
var searchResults = from student in students
where student.Lastname.StartsWith("Smith")
select student;
This code will search in your students list and return three students : Smith, SmithFoo and SmithBar
Thats how I did in the end. Sorry I forgot to answer this one.
public int search(object sender, List<albums> al)
{
int i = -1;
TextBox txt = (TextBox)sender;
foreach (albums dc in al)
{
if ((dc.artist == txt) ||(dc.tag == txt))
{
i = (al.IndexOf(dc));
}
}
return i;
}

Check if a List Column Exists using SharePoint Client Object Model?

Using the Client Object Model (C#) in SharePoint 2010, how can I determine if a specified column (field) name exists in a given List?
Thanks, MagicAndi.
Just found this while searching for the same thing, but it looks like Sharepoint 2010 has something built in for this, at least for the Server model: list.Fields.ContainsField("fieldName");
Not sure if it exists for Client side though. Figured it would be a good place to store this information however.
Server Object Model
string siteUrl = "http://mysite";
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["my forum"];
for (int i = 0; i < list.Fields.Count; i++)
{
if (list.Fields[i].Title == "xyz")
{
-
-
}
}
}
}
Client Object Model
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List List = clientContext.Web.Lists.GetByTitle("my forum");
for (int i = 0; i < list.Fields.Count; i++)
{
if (list.Fields[i].Title == "xyz")
{
-
-
}
}
The following method demonstrates how to determine whether a specified column exists in a List using CSOM:
static class FieldCollectionExtensions
{
public static bool ContainsField(this List list,string fieldName)
{
var ctx = list.Context;
var result = ctx.LoadQuery(list.Fields.Where(f => f.InternalName == fieldName));
ctx.ExecuteQuery();
return result.Any();
}
}
Usage
using(var ctx = new ClientContext(webUrl))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
if(list.ContainsField("Title")){
//...
}
}
Here's an extension code (CSOM) for sharepoint list
public static bool DoesFieldExist(this List list, ClientContext clientContext, string internalFieldname)
{
bool exists = false;
clientContext.Load(list.Fields, fCol => fCol.Include(
f => f.InternalName
).Where(field => field.InternalName == internalFieldname));
clientContext.ExecuteQuery();
if (list.Fields != null && list.Fields.Count > 0)
{
exists = true;
}
return exists;
}
usage
List targetList = this.Context.Web.Lists.GetById(<ListID>);
targetList.DoesFieldExist(<ClientContext>, <Field internal Name>)
enjoy :)
I ended up retrieving the details of the list's fields prior to my operation, and saving them in a generic list of structs (containing details of each field). I then query this (generic) list to see if the current field actually exists in the given (SharePoint) list.
// Retrieve detail sof all fields in specified list
using (ClientContext clientContext = new ClientContext(SharePointSiteUrl))
{
List list = clientContext.Web.Lists.GetByTitle(listName);
_listFieldDetails = new List<SPFieldDetails>();
// get fields name and their types
ClientObjectPrototype allFields = list.Fields.RetrieveItems();
allFields.Retrieve( FieldPropertyNames.Title,
FieldPropertyNames.InternalName,
FieldPropertyNames.FieldTypeKind,
FieldPropertyNames.Id,
FieldPropertyNames.ReadOnlyField);
clientContext.ExecuteQuery();
foreach (Field field in list.Fields)
{
SPFieldDetails fieldDetails = new SPFieldDetails();
fieldDetails.Title = field.Title;
fieldDetails.InternalName = field.InternalName;
fieldDetails.Type = field.FieldTypeKind;
fieldDetails.ID = field.Id;
fieldDetails.ReadOnly = field.ReadOnlyField;
listFieldDetails.Add(fieldDetails);
}
}
// Check if field name exists
_listFieldDetails.Exists(field => field.Title == fieldName);
// Struct to hold details of the field
public struct SPFieldDetails
{
public string Title { get; set; }
public string InternalName { get; set; }
public Guid ID { get; set; }
public FieldType Type { get; set; }
public bool ReadOnly { get; set; }
}
Some good answers above. I personally used this one:
List list = ctx.Web.Lists.GetByTitle("Some list");
FieldCollection fields = list.Fields;
IEnumerable<Field> fieldsColl = ctx.LoadQuery(fields.Include(f => f.InternalName));
ctx.ExecuteQuery();
bool fieldMissing = fieldsColl.Any(f => f.InternalName != "Internal_Name");
You can also use 'Where' after Include method and check if returned collection/field is null. It's about personal preference, because both options are querying on client side.
I prefer the SharePoint Plus Library as it is really clean:
http://aymkdn.github.io/SharepointPlus/symbols/%24SP%28%29.list.html
$SP().list("My List").get({
fields:"Title",
where:"Author = '[Me]'"
},function getData(row) {
console.log(row[0].getAttribute("Title"));
});
You could setup a for loop to loop through the row and check if the column you're looking for exists.
A cut down and simplified version of Mitya's extension method:
public static bool FieldExists(this List list, string internalFieldname)
{
using (ClientContext clientContext = list.Context as ClientContext)
{
clientContext.Load(list.Fields, fCol => fCol.Include(
f => f.InternalName
).Where(field => field.InternalName == internalFieldname));
clientContext.ExecuteQuery();
return (list.Fields != null) && (list.Fields.Count > 0);
}
}
There's no need to pass in a separate client context parameter when you can already use the context that comes in with the list.
to much code use this
load Fields first then
bool exists= clientContext2.Site.RootWeb.Fields.Any(o => o.Id.ToString() == a.Id.ToString());

Resources